Class: ActiveDecorator::Decorator

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/active_decorator/decorator.rb

Instance Method Summary collapse

Constructor Details

#initializeDecorator

Returns a new instance of Decorator.



11
12
13
# File 'lib/active_decorator/decorator.rb', line 11

def initialize
  @decorators = {}
end

Instance Method Details

#decorate(obj) ⇒ Object

Decorates the given object. Plus, performs special decoration for the classes below:

Array: decorates its each element
Hash: decorates its each value
AR::Relation: decorates its each record lazily
AR model: decorates its associations on the fly

Always returns the object, regardless of whether decorated or not decorated.

This method can be publicly called from anywhere by ‘ActiveDecorator::Decorator.instance.decorate(obj)`.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/active_decorator/decorator.rb', line 25

def decorate(obj)
  return obj if defined?(Jbuilder) && (Jbuilder === obj)

  case obj
  when Array
    obj.each {|e| decorate e }
  when Hash
    obj.each_value {|v| decorate v }
  when nil, true, false
    # Do nothing
  else
    if defined? ActiveRecord
      if obj.is_a? ActiveRecord::Relation
        return decorate_relation obj
      elsif ActiveRecord::Base === obj
        obj.extend ActiveDecorator::Decorated unless ActiveDecorator::Decorated === obj
      end
    end

    d = decorator_for obj.class
    obj.extend d if d && !(d === obj)
  end

  obj
end

#decorate_association(owner, target) ⇒ Object

Decorates AR model object’s association only when the object was decorated. Returns the association instance.



53
54
55
# File 'lib/active_decorator/decorator.rb', line 53

def decorate_association(owner, target)
  (ActiveDecorator::Decorated === owner) ? decorate(target) : target
end