2013-12-17 61 views
2

我正在使用configtron來存儲我的配置值。除非範圍在類的方法內,否則我可以毫無問題地訪問配置值。configtron單身?爲什麼我不能在我的課堂上訪問configtron

我使用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單。

我錯過了什麼?

回答

2

當前實現的configatron

module Kernel 
    def configatron 
    @__configatron ||= Configatron::Store.new 
    end 
end 
here

由於Kernel被包括在Object,使得在每一個對象中的可用方法。但是,b/c方法只是簡單地設置一個實例變量,該存儲將只對每個實例可用。奇怪的選擇是一個寶石,他的整個工作是提供一個全球性的商店。

在V2.4他們使用類似的方法來訪問一個單身,這可能從here

看起來工作更好

module Kernel 
    # Provides access to the Configatron storage system. 
    def configatron 
    Configatron.instance 
    end 
end 

喜歡,你可以解決這個自己使用require 'configatron/core'來避免猴子 - 補丁,並提供你自己的單身包裝。

+0

我所能說的全部都是感謝和驚訝。 – John

相關問題