Skip to content

Instantly share code, notes, and snippets.

@miyohide
Created February 28, 2014 11:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miyohide/9269550 to your computer and use it in GitHub Desktop.
Save miyohide/9269550 to your computer and use it in GitHub Desktop.
メソッドの呼び出し直後と終了直後にログを出力したい(解決編)
module AddLogging
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def method_added(name)
# すでにhookメソッドがあったり、without_hookメソッドがある場合は定義しない
return if /hook/.match(name.to_s) || method_defined?("#{name}_without_hook")
# 開始と終了時にメッセージを出す
hook = <<-EOS
def #{name}_hook
puts 'Method #{name} start'
#{name}_without_hook
puts 'Method #{name} end'
end
EOS
self.class_eval(hook)
# 元々のメソッドは_without_hookをつけて定義
a1 = "alias #{name}_without_hook #{name}"
self.class_eval(a1)
# _hookメソッドは、元々のメソッド名で定義
a2 = "alias #{name} #{name}_hook"
self.class_eval(a2)
end
end
end
class Hello
include AddLogging
def say_hello
puts "hello"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment