Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
Shpigford Avatar asked May 12 '10 13:05

Shpigford


People also ask

What is a Rails initializer?

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.

How do I run Rails server in developer mode?

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 .

Where is RAILS_ENV defined?

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.


2 Answers

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
like image 34
Andrei Avatar answered Oct 28 '22 00:10

Andrei


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
like image 100
jigfox Avatar answered Oct 28 '22 01:10

jigfox