动态添加单例方法

时间:2012-12-11 19:33:55

标签: ruby

我想定义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

如何修复错误行以使其有效?

1 个答案:

答案 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]