【问题标题】:Rails initializer for development and production用于开发和生产的 Rails 初始化程序
【发布时间】:2011-02-18 15:02:39
【问题描述】:

我在/config/initializers/chargify.rb中有以下代码

Chargify.configure do |c|
  c.subdomain = 'example'
  c.api_key   = '123xyz'
end

但我有不同的开发和生产设置。

那么,如何根据环境获得一组不同的变量值?

【问题讨论】:

  • Josh,这就是 Baremetrics MVP 的内容吗?历史正在这里形成:)
  • @JanKlimo 哈哈,不。这比 Baremetrics 成为我脑海中的一个想法早了 3 年多。 :P

标签: ruby-on-rails environment initializer


【解决方案1】:

我会为此创建一个配置文件 (config/chargify.yml):

development:
  subdomain: example
  api_key: 123abc
production:
  subdomain: production_domain
  api_key: 890xyz

然后像这样改变你的初始化器:

chargify_config_file = File.join(Rails.root,'config','chargify.yml')
raise "#{chargify_config_file} is missing!" unless File.exists? chargify_config_file
chargify_config = YAML.load_file(chargify_config_file)[Rails.env].symbolize_keys

Chargify.configure do |c|
  c.subdomain = chargify_config[:subdomain]
  c.api_key   = chargify_config[:api_key]
end

【讨论】:

  • 对任何从上方剪切和粘贴的人的快速警告:sudomain: example 应为 subdomain: example
【解决方案2】:

怎么样:

Chargify.configure do |c|
  if Rails.env.production?
    # production settings
    c.api_key   = '123xyz'
  else
    # dev. and test settings
    c.api_key   = '123xyz'
  end
end

更好的是,您可以使用case 块减少重复:

Chargify.configure do |c|
  c.subdomain = 'example'
  c.api_key   = case
    when Rails.env.production?
      '123xyz'
    when Rails.env.staging?
      'abc123'
    else
      'xyz123'
    end
end

【讨论】:

    【解决方案3】:

    如果您需要针对不同的环境进行不同的设置,最好将它们放在各自的环境文件中,例如config/environments/development.rb

    如果您绝对坚持将它们放入初始化程序(但请不要,这就是环境文件的用途),您可以使用 case 语句并检查 Rails.env 的值,它会返回名称当前环境的字符串。

    【讨论】:

    • application.rb 中的 cmets 将配置放在这些文件上,并将其放在初始化程序目录中的文件中。
    【解决方案4】:

    我建议你使用环境变量

    Chargify.configure do |c|
      c.subdomain = ENV['APP_SUBDOMAIN']
      c.api_key = ENV['API_KEY']
    end
    

    并在 ~/.bashrc 或 ~/.profile 中设置适当的变量 但请注意:这必须为 Rails 实例正在运行的同一用户设置。例如。在 capistrano 中指定的部署用户是您用于部署的用户

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多