Search code examples
ruby-on-railsenvironmentinitializer

Rails initializer for development and production


I have the following code in /config/initializers/chargify.rb

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

But I have different settings for development and production.

So, how would I have a different set of variables values based on environment?


Solution

  • I would create a config file for this (config/chargify.yml):

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

    And then change your Initializer like this:

    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