Module: StrongPresenter::ControllerAdditions::ClassMethods

Defined in:
lib/strong_presenter/controller_additions.rb

Instance Method Summary collapse

Instance Method Details

#presents(*variables, options = {}) {|Presenter| ... } ⇒ Object

Defines a helper method to access instance variables wrapped in presenters.

Examples:

# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
  presents :article
  presents :comments, with: ArticleCommentsPresenter, only: :show
  presents :comments, with: CommentsPresenter, only: :index { |presenter| presenter.permit(:author, :text) }

  def show
    @article = Article.find(params[:id])
  end
end

# app/views/articles/show.html.erb
<%= article.presented_title %>

Parameters:

  • variables (Symbols*)

    names of the instance variables to present (without the @).

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :with (Presenter, CollectionPresenter) — default: nil

    presenter class to use. If nil, it is inferred from the instance variable.

  • :only (Symbols*) — default: nil

    apply presenter only on these controller actions.

  • :except (Symbols*) — default: nil

    don't apply presenter on these controller actions.

Yields:

  • (Presenter)

    code to execute when presenter is initialized



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/strong_presenter/controller_additions.rb', line 35

def presents(*variables, &block)
  options = variables.extract_options!
  options.assert_valid_keys(:with, :only, :except)

  constructor = StrongPresenter::PresenterHelperConstructor.new(self, block, options)

  variables.each do |variable|
    constructor.call(variable)
    helper_method variable
  end
end