Created
April 5, 2020 07:18
-
-
Save havenwood/62aed5908f3f502b9abe7b9b774dad5a to your computer and use it in GitHub Desktop.
Before all methods hook example for stapler on #ruby IRC
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
| class BeforeAll < Module | |
| def initialize(before_method) | |
| @before_method = before_method | |
| end | |
| def prepended(base) | |
| base.instance_methods(false).each do |method_name| | |
| this_method = base.instance_method(method_name) | |
| before_method = @before_method | |
| define_method(method_name) do |*args, **kwargs, &block| | |
| method(before_method).call | |
| this_method.bind_call(self, *args, **kwargs, &block) | |
| end | |
| end | |
| end | |
| end | |
| class Foo | |
| def foo | |
| puts 'Foo' | |
| end | |
| private | |
| def bar | |
| puts 'Before ...' | |
| end | |
| prepend BeforeAll.new(:bar) | |
| end | |
| Foo.new.foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment