/classic_presenter

A simple Presenter Pattern for Rails Applications

Primary LanguageRuby

Classic Presenter

Presenter Pattern for Rails Applications

Installation

gem install classic_presenter

Usage

  • 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 %>

Additional details

  • 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 %>