Module: Procemon::Hooks
- Defined in:
- lib/procemon/hooks.rb
Instance Method Summary collapse
-
#inject_instance_method(method, options = {}, &block) ⇒ Object
(also: #extend_instance_method, #hook_instance_method)
this will inject a code block to a target singleton method by default the before or after sym is not required.
-
#inject_singleton_method(method, options = {}, &block) ⇒ Object
(also: #extend_singleton_method, #hook_singleton_method)
this will inject a code block to a target instance method by default the before or after sym is not required.
Instance Method Details
#inject_instance_method(method, options = {}, &block) ⇒ Object Also known as: extend_instance_method, hook_instance_method
this will inject a code block to a target singleton method by default the before or after sym is not required
options can be:
- add: 'before'/'after' add your code into method before the original part of after
Test.inject_instance_method :hello, params: "merged" do |*args|
puts "singleton on a instance method and "+args[0]
end
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/procemon/hooks.rb', line 51 def inject_instance_method(method,={},&block) unbound_method= self.instance_method(method).clone self.class_eval do undef_method method define_method( method, Proc.new { |*args| begin case [:add].to_s.downcase[0] when "a" unbound_method.bind(self).call(*args) block.call_with_binding(self.binding?,*args) else block.call_with_binding(self.binding?,*args) unbound_method.bind(self).call(*args) end end } ) end end |
#inject_singleton_method(method, options = {}, &block) ⇒ Object Also known as: extend_singleton_method, hook_singleton_method
this will inject a code block to a target instance method by default the before or after sym is not required
options can be:
- add: 'before'/'after' add your code into method before the original part of after
Test.inject_singleton_method :hello do |*args|
puts "singleton extra, so #{args[0]}"
end
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/procemon/hooks.rb', line 13 def inject_singleton_method(method,={},&block) original_method= self.method(method).clone self.singleton_class.__send__ :undef_method, method # source code begin sources= nil case [:add].to_s.downcase[0] when "a" sources= [original_method.to_proc,block] else sources= [block,original_method.to_proc] end end self.define_singleton_method method do |*arguments| sources.each do |proc| proc.call_with_binding(original_method.binding?,*arguments) end end return nil end |