Module: Anchor::Hooks::Hooked

Included in:
ClassMethods
Defined in:
lib/anchor/hooks.rb

Overview

Hooked

Instance Method Summary collapse

Instance Method Details

#add_hook_for_method(type, method, &block) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/anchor/hooks.rb', line 31

def add_hook_for_method(type, method, &block)
  level, name = case method; when Hash; method.shift; when Symbol; [:instance, method]; end        
  # set hooks on metaclass instance, not self, if method has to be class method or self is a Object
  in_scope = :metaclass if level == :singleton or not self.is_a?(Class) 
  return Anchor.hook(class << self; self; end) do
    self.method(type).call(name, &block)
  end if in_scope == :metaclass        
  # replace orginal method with hooked method          
  instance_exec do
    hooks = @hooks ||= {}
    @hooks[name] ||= {}
    @hooks[name][type] ||= []
    @hooks[name][type] << block
    orginal_methods = @orginal_methods ||= {}
    
    unless @orginal_methods[name]
      orginal_methods[name] = self.instance_method(name)
      define_method name do |*args, &block|
        ihooks  = hooks[name] # instance hooks
        orginal_method = orginal_methods[name].bind(self)
        # before
        ihooks[:before].each {|proc| proc.call(*args, &block) } if ihooks[:before]
        # TODO: around
        retval=orginal_method.call(*args, &block)
        # after
        ihooks[:after].each {|proc| proc.call(*args, &block) } if ihooks[:after]
        retval
      end
    end
    
  end
end

#add_hook_for_methods(type, *methods, &block) ⇒ Object Also known as: add_hook



26
27
28
# File 'lib/anchor/hooks.rb', line 26

def add_hook_for_methods(type, *methods, &block)
  methods.flatten.each {|method| add_hook_for_method(type, method, &block)}      
end