Class: Gifted::Decorator

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

Instance Method Summary collapse

Constructor Details

#initializeDecorator

Returns a new instance of Decorator.



12
13
14
# File 'lib/gifted/decorator.rb', line 12

def initialize
  @@decorators = {}
end

Instance Method Details

#decorate(obj) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/gifted/decorator.rb', line 16

def decorate(obj)
  if obj.is_a?(Array)
    obj.each { |r| decorate r }
  elsif obj.is_a?(Hash)
    obj.each_value { |v| decorate v }
  elsif obj.is_a?(ActiveRecord::Relation)
    extend_with_relation_decorator obj
  else
    extend_with_decorated obj

    return obj unless (d = decorator_for(obj.class))

    # !! The original monkey patched code.
    # obj.extend d unless obj.is_a? d

    # The new hotness, which mixes in a single "parent" method called `gift`, that isolates all
    # decorated methods; avoiding confusion as to which methods are decorated and which are not.
    #
    # Example:
    #   object.gift.my_decorated_method
    #   object.my_non_decorated_method
    #
    # Instead of extending (decorating) the given object with the decorator module, this extends
    # it with Gifted::Gift, and sets the default decorator as the calculated decorator module
    # above. Gifted::Gift extends the object with one method; `gift`, which returns the
    # default decorator.
    obj.extend(::Gifted::Gift).default_decorator = d unless obj.is_a? ::Gifted::Gift
  end

  obj
end

#decorate_association(owner, target) ⇒ Object

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



50
51
52
# File 'lib/gifted/decorator.rb', line 50

def decorate_association(owner, target)
  owner.is_a?(Gifted::Decorated) ? decorate(target) : target
end