Presenters

Role of Presenter

The presenter is a read-only class to pass data to a view. The data can come from the database, external service, or any structure of data.

  • Includes the logic for a given View or partial.
  • Allow logic-less views (templates) and easier unit testing / performance optimisations.
  • Allow the Controller to instantiate a single variable for the View.

Location

  • app/presenters/
  • Should be suffix with _presenter.rb

Structure of a Presenter

  • A Presenter is a standalone class.
  • A Presenter can include Rails.application.routes.url_helpers
  • A Presenter is initialized with data.

Dos

  • Use attr_accessor
  • You can format using Decorators
  • You can fetch data with Query Objects if needed (complex structures).
  • Use Presenter in Views only.

Don'ts

  • A Presenter is a read-only class and shouldn't mutate data, never.

Code

require 'cgi'

module Handbook
  class ThemePresenter

    include Rails.application.routes.url_helpers
    include Handbook::PreviewHelpers

    def initialize(theme, current_role, locales)
      @theme = theme
      @current_role = current_role
      @locales = locales
    end

    def title
      @theme.title
    end

    def menu
      MenuPresenter.new(@theme.school, @theme, @current_role, @locales)
    end

    def presentation
      return if @theme.description.empty?
      simple_format(@theme.description, {}, wrapper_tag: 'div')
    end

    def single_article?
      filtered_items.count == 1
    end

    def main_content
      if filtered_items.count == 1
        ArticlePresenter.new(filtered_items.first, @current_role, @locales)
      else
        filtered_items.map { |article| decorate_article(article) }
      end
    end

    private

    def filtered_items
      FilteredResources.present(
        @theme.articles,
        @current_role,
        locales: @locales
      )
    end

  end
end

results matching ""

    No results matching ""