I want to change the logging level of an app开发者_C百科lication (ruby).
require 'logger'
config = { :level => 'Logger::WARN' }
log = Logger.new STDOUT
log.level = Kernel.const_get config[:level]
Well, the irb wasn't happy with that and threw "NameError: wrong constant name Logger::WARN" in my face. Ugh! I was insulted.
I could do this in a case/when to solve this, or do log.level = 1, but there must be a more elegant way!
Does anyone have any ideas?
-daniel
Why don't you just use the literal constant in your config
hash?
config = { :level => Logger::WARN }
Then you don't have to fool around with const_get
or anything like that; you can simply do log.level = config[:level]
.
If it absolutely must be a string, you can drop the namespace prefix and call const_get
on the Logger
module:
irb(main):012:0> Logger.const_get 'WARN'
=> 2
If it really really has to be the qualified string, you might try using this blog's qualified_const_get
method (which is not a built-in!).
精彩评论