Domanda

There has to be a better way to do this:

require 'log4r'

class PaddedLogger

  attr_accessor :logger, :padding

  def initialize(args)
    @logger = Log4r::Logger.new args[:name]
    @padding = args[:padding]
  end

  def debug(system, message)
    system = "[#{system}]"
    @logger.debug "#{system.ljust(@padding)}#{message}"
  end

  def info(system, message)
    system = "[#{system}]"
    @logger.info "#{system.ljust(@padding)}#{message}"
  end

  def warn(system, message)
    system = "[#{system}]"
    @logger.warn "#{system.ljust(@padding)}#{message}"
  end

  def error(system, message)
    system = "[#{system}]"
    @logger.error "#{system.ljust(@padding + 3)}#{message}"
  end

  def fatal(system, message)
    system = "[#{system}]"
    @logger.fatal "#{system.ljust(@padding + 3)}#{message}"
  end
end

It's just a wrapping class to help me get my log4r logs appearing in a specific format, and it works exactly as I need it too, but surely Ruby's meta-programming magic can simplify this so I don't have to constantly repeat myself.

È stato utile?

Soluzione

Something like this maybe?

require 'log4r'

class PaddedLogger

  attr_accessor :logger, :padding

  def initialize(args)
    @logger = Log4r::Logger.new args[:name]
    @padding = args[:padding]
  end

  [:debug, :info, :warn, :error, :fatal].each do |reason|
    define_method reason do |system, message|
      system = "[#{system}]"
      @logger.send reason, "#{system.ljust(@padding)}#{message}"
    end
  end

end

And while you're at it, why not collapse the two lines in the define_method block to one?

@logger.send reason, "[#{system}]".ljust(@padding) + message

Altri suggerimenti

Here is and alternative solution using method_missing:

class TestClass

  @@methods = [:upcase, :other_methods_to_catch]

  def initialize
    @message = 'hello'
  end 

  def method_missing name, *args
     super unless @@methods.include? name
     @message.send(name, *args)
  end

end 

x = TestClass.new

p x.upcase #=> HELLO
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top