/gist:976c97473472734f496e Secret
Created
January 20, 2014 20:54
Revisions
-
depy created this gist
Jan 20, 2014 .There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,59 @@ class MyClass def abc(i) p "abc" p i 42 end end module StreetWalker def self.included(base) base.extend(self) end def hook_before(method, clazz, &block) temp_method = method.to_s+"_before_hook" hook(method, temp_method, clazz, block, nil) end def hook_after(method, clazz, &block) temp_method = method.to_s+"_after_hook" hook(method, temp_method, clazz, nil, block) end private def hook(method, temp_method, clazz, before_block, after_block) clazz.instance_eval do alias_method temp_method, method define_method(method) do |*args| before_block.call if before_block result = send(temp_method, *args) after_block.call(result) if after_block end end end end module MyClassTestHooks include StreetWalker hook_before :abc, MyClass do |result| p "BEFORE!" end hook_after :abc, MyClass do |result| p "AFTER" p "Result > "+result.to_s end end v = MyClass.new v.abc 1