Last active
November 16, 2015 14:22
-
-
Save kymmt90/bcad30ff36f1f13a8637 to your computer and use it in GitHub Desktop.
This file contains 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 HookMethod | |
def hook_method(hook, *methods) | |
methods.each do |method| | |
orig = "#{method}_without_logging".to_sym | |
if instance_methods.include?(orig) | |
raise NameError, "#{orig} isn't a unique name" | |
end | |
alias_method orig, method | |
define_method(method) do |*args, &block| | |
result = send(orig, *args, &block) | |
send(hook) | |
result | |
end | |
end | |
end | |
end | |
def print_message | |
puts 'hook message' | |
end | |
Array.extend HookMethod | |
Array.hook_method(:print_message, :first, :at) | |
puts [1, 2, 3].first | |
puts [2, 3, 4].at(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment