Created
June 5, 2017 15:07
-
-
Save pachacamac/70fc6358c42a982c38b2b31742053878 to your computer and use it in GitHub Desktop.
add before and after hooks
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 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