Module: Advice
- Included in:
- DbDom::Rexml::DynamicElement
- Defined in:
- lib/advice.rb
Overview
simple advice support see: refactormycode.com/codes/656-method-hooks-in-ruby-any-cleaner
Instance Method Summary collapse
- #advise(h = {}, *methods) ⇒ Object
- #advise_after(sym, *methods) ⇒ Object
- #advise_before(sym, *methods) ⇒ Object
Instance Method Details
#advise(h = {}, *methods) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/advice.rb', line 12 def advise(h = {}, *methods) methods.each do |meth| # save original method hook_method = RUBY_VERSION >= '1.9.0' ? :"__#{meth}__hooked__" : "__#{meth}__hooked__" # create the copy of the hooked method alias_method hook_method, meth # declare the original private private hook_method # define our new replacement method define_method meth do |*args| if h.has_key?(:before) method(h[:before]).call meth, args end # call the original method val = send(:"__#{meth}__hooked__", *args) if h.has_key?(:after) method(h[:after]).call meth, args end val end end end |
#advise_after(sym, *methods) ⇒ Object
8 9 10 |
# File 'lib/advice.rb', line 8 def advise_after(sym, *methods) advise({ :after => sym }, *methods) end |
#advise_before(sym, *methods) ⇒ Object
4 5 6 |
# File 'lib/advice.rb', line 4 def advise_before(sym, *methods) advise({ :before => sym }, *methods) end |