Presenter Pattern for Rails Applications
gem install classic_presenter
-
In your Gemfile you should set:
gem 'classic_presenter'
-
Create a simple ActiveRecord class that you want to present:
class Product < ActiveRecord::Base end
-
Create a presenter class inheriting from ClassicPresenter::Base:
class ProductPresenter < ClassicPresenter::Base def display_name if user context.content_tag :strong, name else context.link_to name, context.product_path end end def display_description context.render "products/description", :product => self end end
-
In your view, show.html.erb for example, you can present your Product object using this syntax:
<% present ProductPresenter, @product, :user => current_user do |presenter| %> <%= presenter.display_name %> <%= presenter.display_description %> <% end %>
-
We can pass many objects to the presenter. In this example we are using :user => current_user and current_user is a helper that returns a User that is logged in. But we can use this for example:
<% present ProductPresenter, @product, :foo => "bar", :bar => "foo" do |presenter| %>
-
Since ClassicPresenter::Base is a Decorator, it implements the “transparent interface” requirements of the Gang of Four’s definition. This means that when we call some method in ProductPresenter, it will be delegated to the decorated object (in this case Product), like this:
#products_controller.rb @product = ProductPresenter.new(Product.find(params[:id])) #show.html.erb <%= @product.name %> <%= @product.display_name %>