Last active
December 17, 2015 16:39
-
-
Save ainame/5640209 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 MethodCallerLogger | |
module ClassMethods | |
LOG_FORAMT = "%s at %s:L%s" | |
def parse_caller(_caller) | |
if /^(.+?):(\d+)(?::in `(.*)')?/ =~ _caller | |
file = $1 | |
line = $2.to_i | |
method = $3 | |
[file, line, method] | |
end | |
end | |
def log_call_point(_caller) | |
file, line, method = parse_caller(_caller[0]) | |
message = sprintf(LOG_FORAMT, method, file, line) | |
warn message | |
end | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
base.class_eval do | |
defined_instance_methods = base.instance_methods(false) | |
defined_instance_methods.each do |method| | |
method_with_logger = (method.to_s + "_with_logger").to_sym | |
method_without_logger = (method.to_s + "_without_logger").to_sym | |
define_method(method_with_logger) do |*args| | |
self.class.log_call_point(caller) | |
__send__ method_without_logger, *args | |
end | |
alias_method method_without_logger, method | |
alias_method method, method_with_logger | |
end | |
singleton_class = (class << base; self end) | |
defined_class_methods = singleton_class.instance_methods(false) | |
defined_class_methods.each do |method| | |
method_with_logger = (method.to_s + "_with_logger").to_sym | |
method_without_logger = (method.to_s + "_without_logger").to_sym | |
singleton_class.class_eval do | |
define_method(method_with_logger) do |*args| | |
self.log_call_point(caller) | |
__send__ method_without_logger, *args | |
end | |
alias_method method_without_logger, method | |
alias_method method, method_with_logger | |
end | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment