17

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?

Shpigford
  • 24,748
  • 58
  • 163
  • 252

4 Answers4

29

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
Freedom_Ben
  • 11,247
  • 10
  • 69
  • 89
jigfox
  • 18,057
  • 3
  • 60
  • 73
5

What about:

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

Better yet, you can reduce duplication with case block:

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
Andrew
  • 227,796
  • 193
  • 515
  • 708
Andrei
  • 10,918
  • 12
  • 76
  • 110
4

If you're going to need different settings for different environments, it's best to put them in the respective environment file, like config/environments/development.rb.

If you absolutely insist on putting them in an initializer (but please don't, that's what the environment files are for), you can use a case statement and inspect the value of Rails.env, which returns the name of the current environment as a string.

ryeguy
  • 65,519
  • 58
  • 198
  • 260
1

I would suggest you to use env variables

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

and set appropriate variables in ~/.bashrc or ~/.profile but note: this must be set for same user as Rails instance is opareting on. E.g. deploy user specified in capistrano is you used that for deployments

user1136228
  • 967
  • 9
  • 22