我正在使用configatron存储我的配置值。我可以毫无问题地访问配置值,除非范围在类的方法之内。
我正在使用ruby 2.0.0的configatron 3.0.0-rc1
这是我在名为“ tc_tron.rb”的单个文件中使用的源
require 'configatron'
class TcTron
def simple(url)
puts "-------entering simple-------"
p url
p configatron
p configatron.url
p configatron.database.server
puts "-------finishing simple-------"
end
end
# setup the configatron. I assume this is a singleton
configatron.url = "this is a url string"
configatron.database.server = "this is a database server name"
# this should print out all the stuff in the configatron
p configatron
p configatron.url
p configatron.database.server
# create the object and call the simple method.
a = TcTron.new
a.simple("called URL")
# this should print out all the stuff in the configatron
p configatron
p configatron.url
p configatron.database.server
当我运行代码时,我得到
{:url=>"this is a url string", :database=>{:server=>"this is a database server name"}}
"this is a url string"
"this is a database server name"
-------entering simple-------
"called URL"
{}
{}
{}
-------finishing simple-------
{:url=>"this is a url string", :database=>{:server=>"this is a database server name"}}
"this is a url string"
"this is a database server name"
在“输入简单”和“完成简单”之间,我不知道为什么我没有得到configatron单例。
我想念什么?
当前的实现configatron
是
module Kernel
def configatron
@__configatron ||= Configatron::Store.new
end
end
从这里
因为Kernel
包含在Object
其中,所以该方法可在每个对象中使用。但是,b / c方法仅设置一个实例变量,该存储将仅对每个实例可用。宝石的奇怪选择,其全部工作是提供可在全球范围内访问的商店。
在v2.4中,他们使用类似的方法访问单例,这可能会更好
module Kernel
# Provides access to the Configatron storage system.
def configatron
Configatron.instance
end
end
从这里
看来您可以自己解决此问题,require 'configatron/core'
而避免使用猴子补丁程序,并提供自己的单例包装器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句