Module: DuckPuncher::Decoration

Included in:
DuckPuncher
Defined in:
lib/duck_puncher/decoration.rb

Overview

Note:

When updating this file please update comment regarding this module in duck_puncher.rb

Instance Method Summary collapse

Instance Method Details

#build_decorator_class(*ducks) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/duck_puncher/decoration.rb', line 8

def build_decorator_class(*ducks)
  targets = ducks.sort.map(&:target)
  decorator_class = DelegateClass(targets.first)
  DuckPuncher.redefine_constant "#{targets.first.to_s.tr(':', '')}Delegator", decorator_class
  ducks.each { |duck| duck.punch target: decorator_class, method: :prepend }
  decorator_class
end

#cached_decoratorsObject



20
21
22
23
24
# File 'lib/duck_puncher/decoration.rb', line 20

def cached_decorators
  @cached_decorators ||= Hash.new do |me, target|
    me[target] = DuckPuncher.decorators.select { |klass, _| klass >= target }
  end
end

#decorate(context, target) ⇒ Object



16
17
18
# File 'lib/duck_puncher/decoration.rb', line 16

def decorate(context, target)
  cached_decorators[target].inject(context) { |me, (_, decorator)| decorator.new(me) }
end

#decoratorsObject



4
5
6
# File 'lib/duck_puncher/decoration.rb', line 4

def decorators
  @decorators ||= ancestral_hash
end

#undecorate(obj) ⇒ Object



26
27
28
29
# File 'lib/duck_puncher/decoration.rb', line 26

def undecorate(obj)
  obj = obj.__getobj__ while obj.respond_to? :__getobj__
  obj
end