我正在使用 configatron 来存储我的配置值。我可以毫无问题地访问配置值,除非范围位于类的方法内。
我正在使用 configatron 3.0.0-rc1 和 ruby 2.0.0
这是我在名为“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
的当前实现是
module Kernel
def configatron
@__configatron ||= Configatron::Store.new
end
end
来自here
由于 Kernel
包含在 Object
中,因此该方法在每个对象中都可用。然而,b/c 该方法只是设置一个实例变量,该存储仅对每个实例可用。对于一个 gem 来说,这是一个奇怪的选择,它的全部工作就是提供一个全局可访问的商店。
在 v2.4 中,他们使用了类似的方法来访问单例,这可能效果更好
module Kernel
# Provides access to the Configatron storage system.
def configatron
Configatron.instance
end
end
来自here
看起来您可以使用 require 'configatron/core'
自己解决这个问题,以避免猴子补丁,并提供您自己的单例包装器。
关于ruby - 配置器是单例吗?为什么我无法访问类(class)中的配置器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623576/