2014-11-20 116 views
0

我繼承了一個工作正常的工具,但是當我嘗試擴展它時,它只是失敗。由於我是新來的Ruby和YAML我真的不知道究竟是爲什麼失敗的原因...YAML Ruby加載多個環境變量

所以我有一個類的配置看起來像這樣

class Configuration 
    def self.[] key 
     @@config[key] 
    end 

    def self.load name 
     @@config = nil 
     io = File.open(File.dirname(__FILE__) + "/../../../config/config.yml") 
     YAML::load_documents(io) { |doc| @@config = doc[name] } 
     raise "Could not locate a configuration named \"#{name}\"" unless @@config 
    end 

    def self.[]=key, value 
     @@config[key] = value 
    end 

    end 
end 

raise "Please set the A environment variable" unless ENV['A'] 
Helpers::Configuration.load(ENV['A']) 

raise "Please set the D environment variable" unless ENV['D'] 
Helpers::Configuration.load(ENV['D']) 

raise "Please set the P environment variable" unless ENV['P'] 
Helpers::Configuration.load(ENV['P']) 

所以我必須第一個版本環境變量A工作正常,然後當我想要集成2個更多的環境變量失敗(它們是不同的鍵/值集)。我做了調試,它看起來像是當它讀取第二個鍵/值時,它刪除了其他的(比如讀取第三個刪除了前面的2,所以最終只有第三個鍵/值par而不是@@ config,而不是所有我需要的值)。

這可能很容易解決這個,任何想法如何?

謝謝!

編輯: 配置文件使用的樣子:

Test: 
    position_x: 「56」 
    position_y: 「56」 

現在我想讓它像

「x56」: 
    position_x: 「56」 

「x15」: 
    position_x: 「15」 

「y56」: 
    position_y: 「56」 

「y15」: 
    position_y: 「15」 

我的想法是,我單獨設置他們,我不需要創建所有組合...

+0

你介意分享'config.yml'文件嗎?乍一看,它看起來像你應該'@@ config = YAML :: load'而不是你在那裏做什麼。 – mudasobwa 2014-11-20 17:58:14

+0

當然,我的意思是這樣做忘了包括它。它使用的是作爲simples就象這樣: 測試: position_x:「56」 position_y:「56」 現在我想讓它像 「X56」: position_x:「56」 「X15 「: position_x:‘15’ ‘Y56’: position_y:‘56’ ‘Y15’: position_y:‘15’ 我的想法是,我單獨設置他們,我並不需要創建所有的組合... – yvuqld 2014-11-20 18:00:07

+0

U請更新你的文章,請。 – mudasobwa 2014-11-20 18:02:37

回答

0

每次撥打load時,都會刪除以前的配置(在行@@config = nil中)。如果您希望配置爲所有文件的合併,您需要將新配置合併到現有配置中,而不是覆蓋它。

事情是這樣的:

def self.load name 
    @@config ||= {} 
    io = File.open(File.dirname(__FILE__) + "/../../../config/config.yml") 
    YAML::load_documents(io) do |doc| 
    raise "Could not locate a configuration named \"#{name}\"" unless doc[name] 
    @@config.merge!(doc[name]) 
    end 
end 

注意,如果代碼被寫,因爲它已經因爲該方法調用一次以上,並且配置預計重置讀取之間,你需要現在明確地重新配置:

class Configuration 

    # ... 

    def reset_configuration 
    @config = {} 
    end 
end 

Helpers::Configuration.reset_configuration 

raise "Please set the A environment variable" unless ENV['A'] 
Helpers::Configuration.load(ENV['A']) 

raise "Please set the D environment variable" unless ENV['D'] 
Helpers::Configuration.load(ENV['D']) 

raise "Please set the P environment variable" unless ENV['P'] 
Helpers::Configuration.load(ENV['P']) 
+0

完美無缺,謝謝!我再次想到了這個問題,但即使將其刪除,我也無法弄清楚如何將它們合併在一起!非常感謝。 – yvuqld 2014-11-20 18:12:05

0

我訪問YAML使用:

YAML::load_file(File.expand_path("../../../config/config.yml", File.dirname(__FILE__))) 

expand_path清理'..'鏈並返回相對於FILE清理的版本。例如:

foo = '/path/to/a/file' 
File.expand_path("../config.yml", File.dirname(foo)) # => "/path/to/config.yml" 

load_file讀取並解析整個文件並將其返回。