我正在制作命令行工具,我正在使用yaml制作配置文件。但是现在我只能在myprogram.yml
与<{1}}相同的目录中访问该工具。
private
CONFIG_FILE = 'myprogram.yml'
def write_config
config = {}
config['username']=@username
config['password']=@password
File.open(CONFIG_FILE, 'w') do |f|
f.write config.to_yaml
end
end
def read_config
config = YAML.load_file(CONFIG_FILE)
@username = config['username']
@password = config['password']
end
如何从计算机上的任何目录访问此文件?
答案 0 :(得分:1)
您想要提供myprogram.yml
文件的绝对目录。现在它将查看执行ruby脚本的目录。通过使其绝对,脚本可以在任何地方运行,并知道在哪里可以找到配置文件。
示例:
private
CONFIG_FILE = '/Users/myuser/config/myprogram.yml'
def write_config
config = {}
config['username']=@username
config['password']=@password
File.open(CONFIG_FILE, 'w') do |f|
f.write config.to_yaml
end
end
def read_config
config = YAML.load_file(CONFIG_FILE)
@username = config['username']
@password = config['password']
end