Skip to content

Instantly share code, notes, and snippets.

@JakubOboza
Created October 6, 2011 13:55
Show Gist options
  • Save JakubOboza/1267452 to your computer and use it in GitHub Desktop.
Save JakubOboza/1267452 to your computer and use it in GitHub Desktop.
Poor Mans Hook
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
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