我想定义Logger对模块的方法,并将它们委托给返回Logger的方法。
module MyLogger
def self.logger
# return a Logger, whatever
end
[:debug, :info, :warn, :error, :fatal] do |_method|
def self._method *args # WRONG. Want to define something named `_method` for the class
logger.send _method, *args
end
end
end
如何修复错误行以使其有效?
答案 0 :(得分:7)
module MyLogger
def self.logger *args
# return a Logger, whatever
end
[:debug, :info, :warn, :error, :fatal].each do |_method|
define_singleton_method _method do |*args|
logger.send _method, *args
end
end
end
p MyLogger.singleton_methods
# => [:logger, :debug, :info, :warn, :error, :fatal]