Module: Decorator::DecoratorAware

Defined in:
lib/method_decorator.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/method_decorator.rb', line 11

def method_missing(name, *args, &block)
  klass = Decorator::DecoratorAware.registry&.key(name)

  return super unless klass

  @decorators ||= []
  @decorators << [klass, args, block]
end

Class Attribute Details

.decoratorsObject

Returns the value of attribute decorators.



8
9
10
# File 'lib/method_decorator.rb', line 8

def decorators
  @decorators
end

.registryObject

Returns the value of attribute registry.



8
9
10
# File 'lib/method_decorator.rb', line 8

def registry
  @registry
end

Instance Attribute Details

#method_decorator_mapObject

Returns the value of attribute method_decorator_map.



5
6
7
# File 'lib/method_decorator.rb', line 5

def method_decorator_map
  @method_decorator_map
end

Instance Method Details

#method_added(name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/method_decorator.rb', line 20

def method_added(name)
  return if @decorators.empty?

  decorators = @decorators.clone
  @decorators = []

  @method_decorator_map ||= {}
  @method_decorator_map[name] = []

  decorators.each do |klass, args, block|
    @method_decorator_map[name] << klass.new(instance_method(name), *args, &block)
  end

  class_eval "
  def #{name}(*args, &block)
    ret = nil
    self.class.method_decorator_map[:#{name}].each do |decorator|
      ret = decorator.call(self, args, ret, &block)
    end
    ret
  end"

  @decorators = []
end