我想我会做一个混合记录来保持我的代码干燥。这是它的外观:
# Mixin that provides shortcuts for logging methods.
module Logging
def self.included(base)
base.class_exec {
@logger_name = base.to_s
@subloggers = []
@logger = Logger.new(STDOUT)
@logger.level = Logger::FATAL
}
end
def logger=(logger)
@logger = logger
@subloggers.each { |obj| obj.logger = logger }
end
def debug(&block)
@logger.debug(@logger_name, &block)
end
def info(&block)
@logger.info(@logger_name, &block)
end
def warn(&block)
@logger.warn(@logger_name, &block)
end
def error(&block)
@logger.error(@logger_name, &block)
end
def fatal(&block)
@logger.fatal(@logger_name, &block)
end
end
理论上,我现在应该能够做到这一点:
class SomeClass
include Logging
def foo_bar
debug { "foo_bar is being executed" }
fatal { "IT'S A TRAP" }
end
end
问题是显然在包含 mixins之前initialize
调用了它,导致失败:
class SomeClass
include Logging
def initialize
@cache = CacheClass.new
@subloggers << @cache # @subloggers is nil
end
end
我无法想象任何方式。我总是在构造函数中创建我的依赖项,并且我需要 Logging mixin 在那时可用。有任何想法吗?