Skip to content

Instantly share code, notes, and snippets.

@pachacamac
Created June 5, 2017 15:07
Show Gist options
  • Select an option

  • Save pachacamac/70fc6358c42a982c38b2b31742053878 to your computer and use it in GitHub Desktop.

Select an option

Save pachacamac/70fc6358c42a982c38b2b31742053878 to your computer and use it in GitHub Desktop.
add before and after hooks
module Hooks
def before(*method_names, &block)
to_prepend = Module.new do
method_names.each do |name|
define_method(name) do |*args, &blk|
yield(name, *args)
super(*args, &blk)
end
end
end
prepend to_prepend
end
def after(*method_names, &block)
to_prepend = Module.new do
method_names.each do |name|
define_method(name) do |*args, &blk|
super(*args, &blk)
yield(name, *args)
end
end
end
prepend to_prepend
end
end
class Example
extend Hooks
before :foo, :bar do |m,*a|
puts "before #{m}(#{a.join(',')})"
end
after :bar do |m,*a|
puts "after #{m}(#{a.join(',')})"
end
def foo(x)
puts "in foo #{x}"
end
def bar
puts "in bar"
end
end
e = Example.new
e.foo 5
e.bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment