Last active
August 29, 2015 14:16
-
-
Save munky69rock/9e81e6326d99f137e2e1 to your computer and use it in GitHub Desktop.
method hook filter for ruby
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 MethodFilter | |
| def before(hook_method, target_methods) | |
| wrap target_methods do |instance, method, args| | |
| instance.send hook_method | |
| instance.send method, *args | |
| end | |
| end | |
| def after(hook_method, target_methods) | |
| wrap target_methods do |instance, method, args| | |
| instance.send method, *args | |
| instance.send hook_method | |
| end | |
| end | |
| private | |
| def wrap(target_methods, &block) | |
| target_methods.each do |target_method| | |
| if method_defined?(target_method) | |
| define_wrap_method(target_method, &block) | |
| else | |
| enqueue target_method, ->{ define_wrap_method(target_method, &block) } | |
| end | |
| end | |
| end | |
| def define_wrap_method(target_method, &block) | |
| renamed_method = rename_original_method(target_method) | |
| alias_method renamed_method, target_method unless method_defined?(renamed_method) | |
| define_method(target_method) do |*args| | |
| instance_eval { block.call(self, renamed_method, args) } | |
| end | |
| end | |
| def method_added(name) | |
| dequeue(name).call if queue.key?(name) | |
| end | |
| def queue | |
| @queue ||= {} | |
| end | |
| def enqueue(name, method) | |
| queue.store(name, method) | |
| end | |
| def dequeue(name) | |
| queue.delete(name) | |
| end | |
| def rename_original_method(method) | |
| "__#{method}" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment