我想问一下铁轨上的红宝石, 可以使用application.yml
设置环境变量我在application.yml
中有这样的代码defaults: &defaults
STORE_URL: https://localhost:3000/
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
并在application.rb上设置配置
Bundler.require(*Rails.groups)
if File.exists?(File.expand_path('../application.yml', __FILE__))
config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
ENV[key] ||= value.to_s unless value.kind_of? Hash
end
end
并将此代码添加到.gitignore
config/appication.yml
.project
当我在终端上测试时,输出应该是这样的,
[1] pry(main)> ENV
=> {"Test1"=>"Tester1",
"Test2"=>"Tester2",
"Test3"=>"Tester3"}
我应该在run rails c development
在Rails 3.0.20和Ruby 1.9.3p545中,当我按类型测试它或在application.yml上添加新的Key和Value时,它的工作非常简单。但是,在Rails 4.1.5和Ruby 2.0.0p541上,它不会像
完整的Application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
if File.exists?(File.expand_path('../application.yml', __FILE__))
config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
ENV[key] ||= value.to_s unless value.kind_of? Hash
end
end
module ModuleUpgrade
class Application < Rails::Application
end
end
需要你的帮助伙伴! 感谢
答案 0 :(得分:0)
我会改变两件事。如何加载文件以及如何获取和合并环境的子哈希:
Bundler.require(*Rails.groups)
file = Rails.root.join('config', 'application.yml')
if File.exists?(file)
config = YAML.load(file).fetch(Rails.env, {})
config.each do |key, value|
ENV[key] ||= value unless value.kind_of?(Hash)
end
end
答案 1 :(得分:0)
我不认为您为application.yml
,File.expand_path('../application.yml', __FILE__)
指定的路径是准确的。试试这个:
app_config = File.join(Rails.root, 'config', 'application.yml')
if File.exists?(app_config)
config = YAML.load(File.read(app_config))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
ENV[key] ||= value.to_s unless value.kind_of? Hash
end
end
如果您不想自己动手,figaro gem会尝试让您更轻松。