我最近用Configatron替换了一个自制的配置模块,但我无法让一个用例工作。
当我尝试使用configatron值作为Object.const_get的参数时,如下所示:
def formatter_class
Object.const_get(configatron.formatter)
end
我得到以下错误:
file.rb:10:in `const_get': can't convert Configatron::Store to String
(Configatron::Store#to_str gives Configatron::Store) (TypeError)
configatron分配如下(简化):
configatron.formatter = case
when condition?
'ExportFormat'
else
'ScreenFormat'
end
即使我执行configatron.formatter = 'ScreenFormat'
,我也会得到相同的错误。
我也尝试过formatter_class
方法的变体。此操作失败:
def formatter_class
Object.const_get(configatron['formatter'])
end
当然,这是成功的,但不能满足我的用例:
def formatter_class
Object.const_get('ScreenFormat')
end
我做错了什么?
我解决了我的问题。事实证明,您可以调用configatron.whatever
,如果它没有初始化,它将返回一个Configatron::Store
。
在访问该值之前,我插入了对configatron.has_key? 'formatter'
的调用。当它返回false时,我发现错误发生在值尚未初始化的代码路径中。一旦我初始化了值,错误就不会再发生了。
当.yml配置文件丢失时发生。或者你正在寻找的钥匙不在那里。
地点:/config/NAME.yml