Skip to content

Instantly share code, notes, and snippets.

@munky69rock
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save munky69rock/9e81e6326d99f137e2e1 to your computer and use it in GitHub Desktop.

Select an option

Save munky69rock/9e81e6326d99f137e2e1 to your computer and use it in GitHub Desktop.
method hook filter for ruby
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