Skip to content

Instantly share code, notes, and snippets.

@depy
Created January 20, 2014 20:54
Show Gist options
  • Save depy/976c97473472734f496e to your computer and use it in GitHub Desktop.
Save depy/976c97473472734f496e to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment