Created
October 6, 2011 13:55
-
-
Save JakubOboza/1267452 to your computer and use it in GitHub Desktop.
Poor Mans Hook
This file contains hidden or 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 characters
module PoorManHook | |
module ClassMethods | |
private | |
def after(*syms, &block) | |
syms.each do |sym| # For each symbol | |
str_id = "__#{sym}__after__" | |
unless private_instance_methods.include?(str_id) | |
alias_method str_id, sym | |
private str_id | |
define_method sym do |*args| | |
ret = __send__ str_id, *args | |
block.call(self, | |
:method => sym, | |
:args => args, | |
:return => ret | |
) | |
ret | |
end | |
end | |
end | |
end | |
def before(*syms, &block) | |
syms.each do |sym| | |
str_id = "__#{sym}__before__" | |
unless private_instance_methods.include?(str_id) | |
alias_method str_id, sym | |
private str_id | |
define_method sym do |*args| | |
block.call(self, | |
:method => sym, | |
:args => args, | |
:return => self | |
) | |
__send__(str_id, *args) | |
end | |
end | |
end | |
end | |
end | |
def PoorManHook.included(base) | |
base.extend(ClassMethods) | |
end | |
end | |
This file contains hidden or 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 characters
class Foo | |
include PoorManHook | |
def bar(one, two) | |
puts one + two | |
end | |
after :bar do |rec, args| | |
puts "after" | |
end | |
before :bar do |rec, args| | |
puts "before" | |
end | |
end | |
Foo.new.bar("1", " 2") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment