在rails中使用Presenters

时间:2013-03-04 22:47:13

标签: 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

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

1 个答案:

答案 0 :(得分:14)

让我们创建一个演示者,将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

现在你的控制器动作应该是这样的:

def show
  # ...
  @presenter = GamesPresenter.new(json)
end

你可以在你的观点中使用它:

<% @presenter.games.each do |game| %>
  ...
<% end %>

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

为了告诉Rails加载apps / presenters /目录以及models /,controllers /,views /等,请将此添加到config / application.rb:

config.after_initialize do |app|
  app.config.paths.add 'app/presenters', :eager_load => true
end