There are a bunch of config files in a Ruby on Rails app. The most popular ist the “database.yml” config file. This is for configuring the database connection in 3 different environments.
Assume you want to have your config file, in the same style as the database.yml file. Where you can configure some program logic depending on the environment. Let’s call this config file “config.yml” and place it under the “config/” directory.
There are now different ways to access the values from the file. I prefer to use this code:
class Settings raw_config = File.read("#{::Rails.root.to_s}/config/config.yml") erb_config = ERB.new(raw_config).result settings = YAML.load(erb_config)[::Rails.env] if settings settings.each { |name, value| instance_variable_set("@#{name}", value) self.class.class_eval { attr_reader name.intern } } end end
Just place it into the “environment.rb” file. My environment.rb file looks like that:
# Load the rails application require File.expand_path('../application', __FILE__) class Settings raw_config = File.read("#{::Rails.root.to_s}/config/config.yml") erb_config = ERB.new(raw_config).result settings = YAML.load(erb_config)[::Rails.env] if settings settings.each { |name, value| instance_variable_set("@#{name}", value) self.class.class_eval { attr_reader name.intern } } end end # Initialize the rails application TrophicWeb::Application.initialize!
Before the initialization of the app the Settings class will read all the key value pairs from the config.yml file. All values are accessible via variable calls. If your config.yml file looks like this:
development: neo4j_service: http://localhost:7474/db/data/cypher test: neo4j_service: http://localhost:7474/db/data/cypher production: neo4j_service: http://ec2-bimbo.aws.com:7474/db/data/cypher
Than you can access the values like this:
Settings.neo4j_service
That’s it.