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?
An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.
Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .
RAILS_ENV is just an environmental variable which is set in the shell or the operating system itself (or when invoking the process). Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With