Class: Draper::Factory

Inherits:
Object
  • Object
show all
Defined in:
lib/draper/factory.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Factory

Creates a decorator factory.

Parameters:

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

    a customizable set of options

Options Hash (options):

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

    decorator class to use. If nil, it is inferred from the object passed to #decorate.

  • context (Hash, #call)

    extra data to be stored in created decorators. If a proc is given, it will be called each time #decorate is called and its return value will be used as the context.



12
13
14
15
16
# File 'lib/draper/factory.rb', line 12

def initialize(options = {})
  options.assert_valid_keys(:with, :context)
  @decorator_class = options.delete(:with)
  @default_options = options
end

Instance Method Details

#decorate(object, options = {}) ⇒ Decorator, CollectionDecorator

Decorates an object, inferring whether to create a singular or collection decorator from the type of object passed.

Parameters:

  • object (Object)

    object to decorate.

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

    a customizable set of options

Options Hash (options):

  • context (Hash)

    extra data to be stored in the decorator. Overrides any context passed to the constructor.

  • context_args (Object, Array) — default: nil

    argument(s) to be passed to the context proc.

Returns:



29
30
31
32
# File 'lib/draper/factory.rb', line 29

def decorate(object, options = {})
  return nil if object.nil?
  Worker.new(decorator_class, object).call(options.reverse_merge(default_options))
end