Created
February 28, 2014 11:32
-
-
Save miyohide/9269550 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 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