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 piece of logic from the show method in controller.How do i move it to the presenter so that it would hold the machine_games JSON response and provide methods to access the games and next/previous page links (and whether or not they exist). {not that familiar with using presenter pattern}
Presenters in Ruby on Rails Presenters are simple classes that sit between the model and the view and provide a nice, DRY object oriented way of working with complex display logic. In Rails, the convention is for them to be located in the app/presenters folder.
Presenters are used to hide implementation details from views. They serve as a go-between for controllers and views. Presenters provide access to controller instance variables. @presenter should be the only instance variable accessed in the view.
A design pattern is a repeatable solution to solve common problems in a software design. When building apps with the Ruby on Rails framework, you will often face such issues, especially when working on big legacy applications where the architecture does not follow good software design principles.
Let's create a presenter for parsing a JSON response into @games
, @next_page
and @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
Now your controller action should 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 %>
And in order to tell Rails to load the apps/presenters/ directory along with models/, controllers/, views/, etc. add this to config/application.rb:
config.after_initialize do |app|
app.config.paths.add 'app/presenters', :eager_load => true
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With