Skip to content

Instantly share code, notes, and snippets.

@betawaffle
Created October 25, 2011 16:57
Show Gist options
  • Save betawaffle/1313482 to your computer and use it in GitHub Desktop.
Save betawaffle/1313482 to your computer and use it in GitHub Desktop.
class RemoveMethodHook < Exception; end
class Module
def before_method(name, &new_method)
raise ArgumentError unless block_given?
old_method = instance_method(name) rescue nil
# new_method = Proc.new
unless old_method.nil?
define_method(name) do |*args|
begin
# module_exec(*args, &new_method) #
new_method.call(self, *args)
rescue RemoveMethodHook
define_method(name, old_method)
end
old_method.bind(self).call(*args)
end
else
define_method(name) do |*args|
begin
# module_exec(*args, &new_method) #
new_method.call(self, *args)
rescue RemoveMethodHook
remove_method(name)
end
nil
end
end
end
def after_method(name, &new_method)
raise ArgumentError unless block_given?
old_method = instance_method(name) rescue nil
# new_method = Proc.new
unless old_method.nil?
define_method(name) do |*args|
ret = old_method.bind(self).call(*args)
begin
# module_exec(*args, &new_method) #
new_method.call(self, *args)
rescue RemoveMethodHook
define_method(name, old_method)
end
ret
end
else
define_method(name) do |*args|
begin
# module_exec(*args, &new_method) #
new_method.call(self, *args)
rescue RemoveMethodHook
remove_method(name)
end
nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment