Skip to content

Instantly share code, notes, and snippets.

@shakemurasan
Last active May 20, 2016 14:03
Show Gist options
  • Save shakemurasan/4b0ad9e5f6172c50a15fba8b207fab3e to your computer and use it in GitHub Desktop.
Save shakemurasan/4b0ad9e5f6172c50a15fba8b207fab3e to your computer and use it in GitHub Desktop.
# ref:
# http://blog.kymmt.com/entry/hook-by-alias-chaining-in-ruby
# http://miyohide.hatenablog.com/entry/2014/02/28/203743
module AddLogging
def self.included(base)
base.extend HookMethod
end
module HookMethod
def hook_class_method(*methods)
methods.each do |method|
orig = "#{method}_without_logging".to_sym
singleton_class.send(:alias_method, orig, method)
define_singleton_method(method) do |*args, &block|
result = send(orig, *args, &block)
puts 'hook message'
result
end
end
end
def hook_instance_method(*methods)
methods.each do |method|
orig = "#{method}_without_logging".to_sym
alias_method orig, method
define_method(method) do |*args, &block|
result = send(orig, *args, &block)
puts 'hook message'
result
end
end
end
end
end
class Hello
include AddLogging
def say_hello(str)
puts "hello, #{str}"
end
def foobar
puts "foobar"
end
class << self
def bar
puts "bar"
end
end
end
# define hook methods.
hello = Hello.new
Hello.hook_instance_method(:say_hello, :foobar)
Hello.hook_class_method(:bar)
# run methods.
hello.say_hello("world")
hello.foobar
Hello.bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment