Skip to content

Instantly share code, notes, and snippets.

@jmazzi
Created December 20, 2011 15:27
Show Gist options
  • Select an option

  • Save jmazzi/1501939 to your computer and use it in GitHub Desktop.

Select an option

Save jmazzi/1501939 to your computer and use it in GitHub Desktop.
module MethodInterception
def method_added(meth)
return unless (@intercepted_methods ||= []).include?(meth) && !@recursing
@recursing = true # protect against infinite recursion
old_meth = instance_method(meth)
define_method(meth) do |*args, &block|
puts 'before'
old_meth.bind(self).call(*args, &block)
puts 'after'
end
@recursing = nil
end
def before_filter(meth)
(@intercepted_methods ||= []) << meth
end
end
class HomeWork
extend MethodInterception
before_filter(:say_hello)
def say_hello
puts "say hello"
end
end
HomeWork.new.say_hello
# before
# say hello
# after
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment