2014-11-20 127 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读取并解析整个文件并将其返回。