Using presenters in rails

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

The above is a small part of the logic from the show method in the controller. How can I transfer it to a presentation so that it saves the JSON machine_games response and provides methods for accessing games and links on the next / previous page (and regardless of whether they exist or not). {not familiar with using the presenter template}

+5
source share
1 answer

Create a presenter to parse the JSON response in @games, @next_pageand @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

Your controller action should now look something like this:

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

And you can use it in your views:

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

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

Rails apps/presenters/ /, /, .., config/application.rb:

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

All Articles