Module: MethodDecorators

Defined in:
lib/method_decorators.rb,
lib/method_decorators/retry.rb,
lib/method_decorators/within.rb,
lib/method_decorators/memoize.rb,
lib/method_decorators/version.rb,
lib/method_decorators/decorator.rb,
lib/method_decorators/deprecated.rb,
lib/method_decorators/precondition.rb

Defined Under Namespace

Classes: Decorator, Deprecated, Memoize, Precondition, Retry, Within

Constant Summary collapse

VERSION =
"0.9.6"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decorate_callable(orig, decorators) ⇒ Object



41
42
43
44
45
# File 'lib/method_decorators.rb', line 41

def self.decorate_callable(orig, decorators)
  decorators.reduce(orig) do |callable, decorator|
    lambda{ |*a, &b| decorator.call(callable, orig.receiver, *a, &b) }
  end
end

.define_others_singleton_method(klass, name, &blk) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/method_decorators.rb', line 47

def self.define_others_singleton_method(klass, name, &blk)
  if klass.respond_to?(:define_singleton_method)
    klass.define_singleton_method(name, &blk)
  else
    class << klass
      self
    end.send(:define_method, name, &blk)
  end
end

Instance Method Details

#method_added(name) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/method_decorators.rb', line 5

def method_added(name)
  super
  orig_method = instance_method(name)

  decorators = Decorator.current_decorators
  return  if decorators.empty?

  if    private_method_defined?(name);   visibility = :private
  elsif protected_method_defined?(name); visibility = :protected
  else                                   visibility = :public
  end

  define_method(name) do |*args, &blk|
    decorated = MethodDecorators.decorate_callable(orig_method.bind(self), decorators)
    decorated.call(*args, &blk)
  end

  case visibility
  when :protected; protected name
  when :private;   private name
  end
end

#singleton_method_added(name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/method_decorators.rb', line 28

def singleton_method_added(name)
  super
  orig_method = method(name)

  decorators = Decorator.current_decorators
  return  if decorators.empty?

  MethodDecorators.define_others_singleton_method(self, name) do |*args, &blk|
    decorated = MethodDecorators.decorate_callable(orig_method, decorators)
    decorated.call(*args, &blk)
  end
end