35
在HOME/path_test/I有:红宝石加载配置(YAML)文件作为源
load_test.rb:
require 'yaml'
cnf = YAML::load(File.open('config.yml'))
puts cnf['Hello']
config.yml:
Hello: world!!!
时在HOME/path_test /我得到如期:
-bash-3.2$ ruby load_test.rb
world!!!
HOME /时(CD ..)我得到
-bash-3.2$ ruby path_test/load_test.rb
path_test/load_test.rb:3:in `initialize': No such file or directory - config.yml (Errno::ENOENT)
from path_test/load_test.rb:3:in `open'
from path_test/load_test.rb:3:in `<main>'
哪个是正确的行为,但不是我所希望的:)
有没有办法来.yml相对于文件加载源文件,而不是相对于当前的工作目录?
解决方案(load_Test.rb):
cnf = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'config.yml'))
编辑:
由于红宝石2.0可以简化
require 'yaml'
fn = File.dirname(File.expand_path(__FILE__)) + '/config.yml'
cnf = YAML::load(File.open(fn))
puts cnf['Hello']
谢谢('')'结尾太多:)]正是我所需要的 – FelixHJ 2012-01-16 10:19:08
这是完整的解决方案(为了清晰起见,分成两行): 'require'yaml' fn = File.dirname(File .expand_path(__ FILE__))+'/config.yml' cnf = YAML :: load(File.open(fn)) puts cnf ['Hello']' – FelixHJ 2012-01-16 10:22:39
嗯,我不能得到格式化工作.... – FelixHJ 2012-01-16 10:24:03