Module: Draper::DecoratesAssigned

Defined in:
lib/draper/decorates_assigned.rb

Instance Method Summary collapse

Instance Method Details

#decorates_assigned(*variables, options = {}) ⇒ Object

Defines a helper method to access decorated instance variables.

Examples:

# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
  decorates_assigned :article

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

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

Parameters:

  • variables (Symbols*)

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

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

Options Hash (options):

  • :with (Decorator, CollectionDecorator) — default: nil

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

  • :context (Hash, #call)

    extra data to be stored in the decorator. If a Proc is given, it will be passed the controller and should return a new context hash.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/draper/decorates_assigned.rb', line 28

def decorates_assigned(*variables)
  factory = Draper::Factory.new(variables.extract_options!)

  variables.each do |variable|
    undecorated = "@#{variable}"
    decorated = "@decorated_#{variable}"

    define_method variable do
      return instance_variable_get(decorated) if instance_variable_defined?(decorated)
      instance_variable_set decorated, factory.decorate(instance_variable_get(undecorated), context_args: self)
    end

    helper_method variable
  end
end