[ACCEPTED]-Best way to create custom config options for my Rails app?-environment

Accepted answer
Score: 195

For general application configuration that 9 doesn't need to be stored in a database 8 table, I like to create a config.yml file within the 7 config directory. For your example, it might look 6 like this:

defaults: &defaults
  audiocast_uri_format: http://blablalba/blabbitybla/yadda

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

This configuration file gets loaded 5 from a custom initializer in config/initializers:

# Rails 2
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]

# Rails 3+
APP_CONFIG = YAML.load_file(Rails.root.join('config/config.yml'))[Rails.env]

If you're 4 using Rails 3, ensure you don't accidentally 3 add a leading slash to your relative config 2 path.

You can then retrieve the value using:

uri_format = APP_CONFIG['audiocast_uri_format']

See 1 this Railscast for full details.

Score: 82

Rails 3 version of initialiser code is as 5 follows (RAILS_ROOT & RAILS_ENV are 4 deprecated)

APP_CONFIG = YAML.load_file(Rails.root.join('config', 'config.yml'))[Rails.env]

Also, Ruby 1.9.3 uses Psych which 3 makes merge keys case sensitive so you'll 2 need to change your config file to take 1 that into account, e.g.

defaults: &DEFAULTS
  audiocast_uri_format: http://blablalba/blabbitybla/yadda

development:
  <<: *DEFAULTS

test:
  <<: *DEFAULTS

production:
  <<: *DEFAULTS
Score: 59

Rails >= 4.2

Just create a YAML file into config/ directory, for 12 example: config/neo4j.yml.

Content of neo4j.yml can be somthing like 11 below(For simplicity, I used default for 10 all environments):

default: &default
  host: localhost
  port: 7474
  username: neo4j
  password: root

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default

in config/application.rb:

module MyApp
  class Application < Rails::Application
    config.neo4j = config_for(:neo4j)
  end
end

Now, your custom config 9 is accessible like below:

Rails.configuration.neo4j['host'] #=>localhost
Rails.configuration.neo4j['port'] #=>7474

More info

Rails official 8 API document describes config_for method as:

Convenience 7 for loading config/foo.yml for the current 6 Rails env.


If you do not want to use a yaml file

As Rails official guide says:

You 5 can configure your own code through the 4 Rails configuration object with custom configuration 3 under the config.x property.

Example

config.x.payment_processing.schedule = :daily
config.x.payment_processing.retries  = 3
config.x.super_debugger = true

These configuration 2 points are then available through the configuration 1 object:

Rails.configuration.x.payment_processing.schedule # => :daily
Rails.configuration.x.payment_processing.retries  # => 3
Rails.configuration.x.super_debugger              # => true
Rails.configuration.x.super_debugger.not_set      # => nil

Official Reference for config_for method | Official Rails Guide

Score: 25

Step 1: Create config/initializers/appconfig.rb 2

require 'ostruct'
require 'yaml'

all_config = YAML.load_file("#{Rails.root}/config/config.yml") || {}
env_config = all_config[Rails.env] || {}
AppConfig = OpenStruct.new(env_config)

Step 2: Create config/config.yml

common: &common
  facebook:
    key: 'asdjhasxas'
    secret : 'xyz'
  twitter:
    key: 'asdjhasxas'
    secret : 'abx'

development:
  <<: *common

test:
  <<: *common

production:
  <<: *common

Step 3: Get constants 1 anywhere in the code

facebook_key = AppConfig.facebook['key']
twitter_key  = AppConfig.twitter['key']
Score: 17

I just wanted to update this for the latest 6 cool stuff in Rails 4.2 and 5, you can now 5 do this inside any of your config/**/*.rb files:

config.x.whatever = 42

(and that's 4 a literal x in there, ie. the config.x. literally 3 must be that, and then you can add whatever 2 you want after the x)

...and this will be 1 available in your app as:

Rails.configuration.x.whatever

See more here: http://guides.rubyonrails.org/configuring.html#custom-configuration

Score: 6

Just some extra info on this topic:

APP_CONFIG = YAML.load_file(Rails.root.join('config', 'config.yml'))[Rails.env].with_indifferent_access

".with_indifferent_access" allows 5 you to access the values in the hash using 4 a string key or with an equivalent symbol 3 key.

eg.
APP_CONFIG['audiocast_uri_format'] => 'http://blablalba/blabbitybla/yadda' APP_CONFIG[:audiocast_uri_format] => 'http://blablalba/blabbitybla/yadda'

Purely a convenience thing, but 2 I prefer to have my keys represented as 1 symbols.

Score: 5

I use something similar to John for Rails 3 3.0/3.1, but I have erb parse the file first:

APP_CONFIG = YAML.load(ERB.new(File.new(File.expand_path('../config.yml', __FILE__)).read).result)[Rails.env]

This 2 allows me to use ERB in my config if I need 1 to, like reading heroku's redistogo url:

production:
  <<: *default
  redis:                  <%= ENV['REDISTOGO_URL'] %>
Score: 2

Rails 4

To create a custom configuration yaml and 5 load it (and make available to your app) similar 4 to how database_configuration.

Create your *.yml, in my case I needed 3 a redis configuration file.

config/redis.yml

default: &default
  host: localhost
  port: 6379

development:
  <<: *default

test:
  <<: *default

production:
  <<: *default
  host: <%= ENV['ELASTICACHE_HOST'] %>
  port: <%= ENV['ELASTICACHE_PORT'] %>

Then load the 2 configuration

config/application.rb

module MyApp
  class Application < Rails::Application

    ## http://guides.rubyonrails.org/configuring.html#initialization-events
    config.before_initialize do
      Rails.configuration.redis_configuration = YAML.load_file("#{Rails.root}/config/redis.yml")
    end

  end
end

Access the values:

Rails.configuration.redis_configuration[Rails.env] similar 1 to how you can have access to your database.yml by Rails.configuration.database_configuration[Rails.env]

Score: 1

Building on Omer Aslam's elegant solution, I 6 decided to convert the keys into symbols. The 5 only change is:

all_config = YAML.load_file("#{Rails.root}/config/config.yml").with_indifferent_access || {}

This allows you to then reference 4 values by symbols as keys, e.g.

AppConfig[:twitter][:key]

This seems 3 neater to my eyes.

(Posted as an answer as 2 my reputation isn't high enough to comment 1 on Omer's reply)

Score: 0

I like simpleconfig. It allows you to have per environment 1 configuration.

Score: 0

see my response to Where is the best place to store application parameters : database, file, code...?

A variation to what you 7 had in that it's a simple reference to another 6 file. It sees that environment.rb isn't 5 constantly updated and doesn't have a heap 4 of app specific stuff in it. Though not 3 a specific answer to your question of 'is 2 it the Rails way?', perhaps there'll be 1 some discussion there about that.

Score: 0

I prefer accessing settings through the 3 global application stack. I avoid excess 2 global variables in local scope.

config/initializers/myconfig.rb

MyAppName::Application.define_singleton_method("myconfig") {YAML.load_file("#{Rails.root}/config/myconfig.yml") || {}}

And access 1 it with.

MyAppName::Application.myconfig["yamlstuff"]
Score: 0

My way to load Settings before Rails initialize

Allows you to use settings in Rails initialization 2 and configure settings per environment

# config/application.rb
Bundler.require(*Rails.groups)

mode = ENV['RAILS_ENV'] || 'development'
file = File.dirname(__FILE__).concat('/settings.yml')
Settings = YAML.load_file(file).fetch(mode)
Settings.define_singleton_method(:method_missing) {|name| self.fetch(name.to_s, nil)}

You 1 could get settings in two ways: Settings['email'] or Settings.email

Score: 0

My best way to custom config, with raise 3 message when setting.yml is missing.

gets 2 loaded from a custom initializer in config/initializers/custom_config.rb

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

@APP_ID = config[:app_id]
@APP_SECRET = config[:app_secret]

Create 1 a YAML in config/setting.yml

development:
  app_id: 433387212345678
  app_secret: f43df96fc4f65904083b679412345678

test:
  app_id: 148166412121212
  app_secret: 7409bda8139554d11173a32222121212

production:
  app_id: 148166412121212
  app_secret: 7409bda8139554d11173a32222121212

More Related questions