我使用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单例。
我遗漏了什么?
发布于 2013-12-17 01:10:45
当前configatron的实现是
module Kernel
def configatron
@__configatron ||= Configatron::Store.new
end
end来自这里
因为Kernel包含在Object中,所以方法在每个对象中都是可用的。但是,b/c方法只设置一个实例变量,该存储将只对每个实例可用。一个宝石的奇怪的选择,它的全部工作是提供一个全球可访问的商店。
在2.4版本中,他们使用了类似的方法来访问单例,这可能更好
module Kernel
# Provides access to the Configatron storage system.
def configatron
Configatron.instance
end
end来自这里
看来您可以自己使用require 'configatron/core'来解决这个问题,以避免猴子补丁,并提供您自己的单例包装器。
https://stackoverflow.com/questions/20623576
复制相似问题