ruby-on-rails - 在 Rails 中使用演示者

标签 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

json = JSON.parse(response.body)
    @games = json['machine-games']

    paging = json['paging']
    if paging
      if paging['next']
        next_page_query = paging['next'].match(/\?.*/)[0]
      @next_page = "/machine_games/search#{next_page_query}"
    end

    if paging['previous']
      previous_page_query = paging['previous'].match(/\?.*/)[0]
      @previous_page = "/machine_games/search#{previous_page_query}"
    end
  end

以上是 Controller 中 show 方法的一小段逻辑。我如何将它移动到演示者,以便它保存 machine_games JSON 响应并提供访问游戏和下一页/上一页链接的方法(以及是否它们存在)。 {不太熟悉使用演示者模式}

最佳答案

让我们创建一个 Presenter 来将 JSON 响应解析为 @games , @next_page@previous_page .

# app/presenters/games_presenter.rb

class GamesPresenter

  attr_reader :games, :next_page, :previous_page

  def initialize json
    @games = json['machine-games']

    paging = json['paging']
    if paging && paging['next']
      next_page_query = paging['next'].match(/\?.*/)[0]
      @next_page = "/machine_games/search#{next_page_query}"
    end

    if paging && paging['previous']
      previous_page_query = paging['previous'].match(/\?.*/)[0]
      @previous_page = "/machine_games/search#{previous_page_query}"
    end
  end

end

现在你的 Controller Action 应该是这样的:
def show
  # ...
  @presenter = GamesPresenter.new(json)
end

您可以在 View 中使用它:
<% @presenter.games.each do |game| %>
  ...
<% end %>

<%= link_to "Previous", @presenter.previous_page %>
<%= link_to "Next", @presenter.next_page %>

为了告诉 Rails 加载 apps/presenters/目录以及模型/、 Controller /、 View /等,将其添加到 config/application.rb:
config.after_initialize do |app|
  app.config.paths.add 'app/presenters', :eager_load => true
end

关于ruby-on-rails - 在 Rails 中使用演示者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212637/

相关文章:

mysql - 我应该使用 MySql 还是 mongodb

ruby-on-rails - 设置列默认值是否会损害数据库空间?

mysql - Ruby on Rails,测试表明列不存在,但在架构上

ruby-on-rails - Rails (Mongoid) 模型中的条件默认值

ruby-on-rails - Ruby on Rails 每次迭代时出错一条记录

ruby-on-rails - 在 Rails 中执行 PUT 后重定向到 GET(状态 : 303) not working

ruby-on-rails - 防止自动机器人向 ruby​​ on rails 应用程序提交表单?

javascript - 在 Rails 应用程序中提前输入 : Append JSON request to only one specific request instead of appending JSON request to every request via prefetch

database - Rails 上所有请求中的随机 "SELECT 1"查询

ruby-on-rails - 命名空间 API 和资源路由