Class: Harbor::Hooks::Chain
- Inherits:
-
Object
- Object
- Harbor::Hooks::Chain
- Defined in:
- lib/harbor/hooks.rb
Class Method Summary collapse
Instance Method Summary collapse
- #after(block) ⇒ Object
- #before(block) ⇒ Object
- #bind! ⇒ Object
- #call(instance, args, blk = nil) ⇒ Object
-
#initialize(target, method_name) ⇒ Chain
constructor
A new instance of Chain.
Constructor Details
#initialize(target, method_name) ⇒ Chain
Returns a new instance of Chain.
37 38 39 40 41 42 43 44 |
# File 'lib/harbor/hooks.rb', line 37 def initialize(target, method_name) @target = target @method_name = method_name @before = [] @after = [] bind! if target.instance_methods.include?(method_name.to_s) end |
Class Method Details
.bind!(target, method_name) ⇒ Object
72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/harbor/hooks.rb', line 72 def self.bind!(target, method_name) target.send(:alias_method, "__hooked_#{method_name}", method_name) target.send(:class_eval, " instance_variable_set(:@__harbor_binding_method, true)\n def \#{method_name}(*args, &block)\n self.class.hooks[\#{method_name.inspect}].call(self, args, block)\n end\n remove_instance_variable(:@__harbor_binding_method)\n EOS\nend\n") |
Instance Method Details
#after(block) ⇒ Object
50 51 52 |
# File 'lib/harbor/hooks.rb', line 50 def after(block) @after << block end |
#before(block) ⇒ Object
46 47 48 |
# File 'lib/harbor/hooks.rb', line 46 def before(block) @before << block end |
#bind! ⇒ Object
84 85 86 |
# File 'lib/harbor/hooks.rb', line 84 def bind! self.class.bind!(@target, @method_name) end |
#call(instance, args, blk = nil) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/harbor/hooks.rb', line 54 def call(instance, args, blk = nil) result = nil catch(:halt) do @before.each do |block| block.call instance end result = instance.send("__hooked_#{@method_name}", *args, &blk) @after.each do |block| block.call instance end result end end |