【发布时间】:2012-09-27 18:47:27
【问题描述】:
我正在编写一个 ruby gem,我想让用户使用您自己的 yaml 文件配置,但我不知道如何测试 user_config.yml 是否存在于 rails 配置路径中。
仅当此文件存在于配置路径中时,我才想使用 user_config.yml。
【问题讨论】:
标签: ruby-on-rails ruby gem yaml
我正在编写一个 ruby gem,我想让用户使用您自己的 yaml 文件配置,但我不知道如何测试 user_config.yml 是否存在于 rails 配置路径中。
仅当此文件存在于配置路径中时,我才想使用 user_config.yml。
【问题讨论】:
标签: ruby-on-rails ruby gem yaml
Rails.root(或早期版本的 Rails 中的RAILS_ROOT)为您提供应用程序根目录的路径。从那里,您可以查看您感兴趣的文件是否存在。
例如
path = File.join(Rails.root, "config", "user_config.yml")
if File.exists?(path)
# do something
end
【讨论】:
Rails.root.join('config', 'user_config.yml')
您可以使用数组类型的 $LOAD_PATH 变量访问 Rails 应用程序的加载路径。
这样
if $LOAD_PATH.include?('/path/where/user/should/put/their/user_config.yml')
# EDIT
config_options = File.new('rails_app/config/user_config.yml', 'r')
else
# EDIT
config_options = File.new('path/to/default/config.yml', 'r')
end
Ruby File class 还有另一种有用的方法,称为#exists?这当然会检查文件是否存在。有关更多信息,请参阅文件类文档。
希望这能让你开始。您的问题比较模糊,如果您需要更多帮助,请回复详细信息。
【讨论】:
configs_hash = YAML.load_file("path/to/config.yml")[RAILS_ENV],其中RAILS_ENV 是“开发”、“测试”等。