首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一个单身的人?为什么我不能访问类中的configatron

一个单身的人?为什么我不能访问类中的configatron
EN

Stack Overflow用户
提问于 2013-12-17 00:13:47
回答 1查看 250关注 0票数 2

我使用configatron来存储我的配置值。我可以毫无问题地访问配置值,除非作用域在类的方法中。

我使用configatron 3.0.0-rc1和ruby 2.0.0

下面是我在一个名为“tc_tron.rb”的文件中使用的源代码

代码语言:javascript
复制
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

当我运行代码时,我得到

代码语言:javascript
复制
{: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单例。

我遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-17 01:10:45

当前configatron的实现是

代码语言:javascript
复制
module Kernel
  def configatron
    @__configatron ||= Configatron::Store.new
  end
end

来自这里

因为Kernel包含在Object中,所以方法在每个对象中都是可用的。但是,b/c方法只设置一个实例变量,该存储将只对每个实例可用。一个宝石的奇怪的选择,它的全部工作是提供一个全球可访问的商店。

在2.4版本中,他们使用了类似的方法来访问单例,这可能更好

代码语言:javascript
复制
module Kernel
  # Provides access to the Configatron storage system.
  def configatron
    Configatron.instance
  end
end

来自这里

看来您可以自己使用require 'configatron/core'来解决这个问题,以避免猴子补丁,并提供您自己的单例包装器。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20623576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档