5

我正在编写一个 ruby​​ gem,我想让用户使用您自己的 yaml 文件配置,但我不知道如何测试 user_config.yml 是否存在于 rails 配置路径中。
仅当此文件存在于配置路径中时,我才想使用 user_config.yml。

4

2 回答 2

13

Rails.root(或RAILS_ROOT在 Rails 的早期版本中)为您提供应用程序根目录的路径。从那里,您可以查看您感兴趣的文件是否存在。

例如

path = File.join(Rails.root, "config", "user_config.yml")
if File.exists?(path)
  # do something
end
于 2012-09-28T00:17:12.590 回答
1

您可以使用数组类型的 $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 类还有另一种有用的方法,称为#exists?这当然会检查文件是否存在。有关更多信息,请参阅文件类文档。

希望这能让你开始。您的问题相当模糊,如果您需要更多帮助,请回复更多详细信息。

于 2012-09-27T19:12:22.903 回答