Easiest way to add multi-environment yaml settings to Rails, Sinatra, Padrino and other Ruby projects.
Easiest way to add multi-environment yaml settings to Rails, Sinatra, Padrino and other Ruby projects.
Config helps you easily manage environment specific settings in an easy and usable manner.
Settings.group.subgroup.setting)Current version supports and is tested for the following interpreters and frameworks:
>= 2.6>= 9.2>= 19.3>= 5.2For Ruby 2.0 to 2.3 or Rails 3 to 4.1 use version 1.x of this gem. For older versions of Rails or Ruby use AppConfig.
For Ruby 2.4 or 2.5 or Rails 4.2, 5.0, or 5.1 use version 3.x of this gem.
Add gem 'config' to your Gemfile and run bundle install to install it. Then run
rails g config:installwhich will generate customizable config file config/initializers/config.rb and set of default settings files:
config/settings.yml
config/settings.local.yml
config/settings/development.yml
config/settings/production.yml
config/settings/test.ymlYou can now edit them to adjust to your needs.
Note: By default, the config environment will match the Rails environment (
Rails.env). This can be changed by settingconfig.environment.
Add the gem to your Gemfile and run bundle install to install it. Then edit app.rb and register Config
register ConfigAdd the gem to your Gemfile and run bundle install to install it. Afterwards in need to register Config in your app and give it a root so it can find the config files.
set :root, File.dirname(__FILE__)
register ConfigAdd the gem to your Gemfile and run bundle install to install it. Then initialize Config manually within your configure block.
Config.load_and_set_settings(Config.setting_files("/path/to/config_root", "your_project_environment"))It's also possible to initialize Config manually within your configure block if you want to just give it some yml paths to load from.
Config.load_and_set_settings("/path/to/yaml1", "/path/to/yaml2", ...)After installing the gem, Settings object will become available globally and by default will be compiled from the files listed below. Settings defined in files that are lower in the list override settings higher.
config/settings.yml
config/settings/#{environment}.yml
config/environments/#{environment}.yml
config/settings.local.yml
config/settings/#{environment}.local.yml
config/environments/#{environment}.local.ymlEntries can be accessed via object member notation:
Settings.my_config_entryNested entries are supported:
Settings.my_section.some_entryAlternatively, you can also use the [] operator if you don't know which exact setting you need to access ahead of time.
# All the following are equivalent to Settings.my_section.some_entry
Settings.my_section[:some_entry]
Settings.my_section['some_entry']
Settings[:my_section][:some_entry]You can reload the Settings object at any time by running Settings.reload!.
You can also reload the Settings object from different config files at runtime.
For example, in your tests if you want to test the production settings, you can:
Rails.env = "production"
Settings.reload_from_files(
Rails.root.join("config", "settings.yml").to_s,
Rails.root.join("config", "settings", "#{Rails.env}.yml").to_s,
Rails.root.join("config", "environments", "#{Rails.env}.yml").to_s
)You can have environment specific config files. Environment specific config entries take precedence over common config entries.
Example development environment config file:
#{Rails.root}/config/environments/development.ymlExample production environment config file:
#{Rails.root}/config/environments/production.ymlYou can load extra sources during initialization by setting the extra_sources configuration option.
Config.setup do |config|
config.extra_sources = [
'path/to/extra_source.yml', # String: loads extra_source.yml
{ api_key: ENV['API_KEY'] }, # Hash: direct hash source
MyCustomSource.new, # Object: custom source object that responds to `load`
]
endThis will also overwrite the same config entries from the main file.
If you want to have local settings, specific to your machine or development environment, you can use the following files, which are automatically .gitignore :
Rails.root.join("config", "settings.local.yml").to_s,
Rails.root.join("config", "settings", "#{Rails.env}.local.yml").to_s,
Rails.root.join("config", "environments", "#{Rails.env}.local.yml").to_sNOTE: The file settings.local.yml will not be loaded in tests to prevent local configuration from causing flaky or non-deterministic tests. Environment-specific files (e.g. settings/test.local.yml) will still be loaded to allow test-specific credentials.
You can add new YAML config files at runtime. Just use:
Settings.add_source!("/path/to/source.yml")
Settings.reload!This will use the given source.yml file and use its settings to overwrite any previous ones.
On the other hand, you can prepend a YML file to the list of configuration files:
Settings.prepend_source!("/path/to/source.yml")
Settings.reload!This will do the same as add_source, but the given YML file will be loaded first (instead of last) and its settings will be overwritten by any other configuration file. This is especially useful if you want to define defaults.
One thing I like to do for my Rails projects is provide a local.yml config file that is .gitignored (so its independent per developer). Then I create a new initializer in config/initializers/add_local_config.rb with the contents
Settings.add_source!("#{Rails.root}/config/settings/local.yml")
Settings.reload!Note: this is an example usage, it is easier to just use the default local files
settings.local.yml,settings/#{Rails.env}.local.ymlandenvironments/#{Rails.env}.local.ymlfor your developer specific settings.
You also have the option to add a raw hash as a source. One use case might be storing settings in the database or in environment variables that overwrite what is in the YML files.
Settings.add_source!({some_secret: ENV['some_secret']})
Settings.reload!You may pass a hash to prepend_source! as well.
Embedded Ruby is allowed in the YAML configuration files. ERB will be evaluated at load time by default, and when the evaluate_erb_in_yaml configuration is set to true.
Consider the two following config files.
#{Rails.root}/config/settings.ymlsize: 1
server: google.com#{Rails.root}/config/environments/development.ymlsize: 2
computed: <%= 1 + 2 + 3 %>
section:
size: 3
servers: [ {name: yahoo.com}, {name: amazon.com} ]Notice that the environment specific config entries overwrite the common entries.
Settings.size # => 2
Settings.server # => google.comNotice the embedded Ruby.
Settings.computed # => 6Notice that object member notation is maintained even in nested entries.
Settings.section.size # => 3Notice array notation and object member notation is maintained.
Settings.section.servers[0].name # => yahoo.com
Settings.section.servers[1].name # => amazon.comThere are multiple configuration options available, however you can customize Config only once, preferably during application initialization phase:
Config.setup do |config|
config.const_name = 'Settings'
# ...
endAfter installing Config in Rails, you will find automatically generated file that contains default configuration located at config/initializers/config.rb.
const_name - name of the object holding your settings. Default: 'Settings'evaluate_erb_in_yaml - evaluate ERB in YAML config files. Set to false if the config file contains ERB that should not be evaluated at load time. Default: truefile_name - name of the file to store general keys accessible in all environments. Default: 'settings' - located at config/settings.ymldir_name - name of the directory to store environment-specific files. Default: 'settings' - located at config/settings/overwrite_arrays - overwrite arrays found in previously loaded settings file. Default: truemerge_hash_arrays - merge hashes inside of arrays from previously loaded settings files. Makes sense only when overwrite_arrays = false. Default: falseknockout_prefix - ability to remove elements of the array set in earlier loaded settings file. Makes sense only when overwrite_arrays = false, otherwise array settings would be overwritten by default. Default: nilmerge_nil_values - nil values will overwrite an existing value when merging configs. Default: true.# merge_nil_values is true by default
c = Config.load_files("./spec/fixtures/development.yml") # => #<Config::Options size=2, ...>
c.size # => 2
c.merge!(size: nil) => #<Config::Options size=nil, ...>
c.size # => nil# To reject nil values when merging settings:
Config.setup do |config|
config.merge_nil_values = false
end
c = Config.load_files("./spec/fixtures/development.yml") # => #<Config::Options size=2, ...>
c.size # => 2
c.merge!(size: nil) => #<Config::Options size=nil, ...>
c.size # => 2Check Deep Merge for more details.
With Ruby 2.1 or newer, you can optionally define a schema or contract (added in config-2.1) using dry-rb to validate presence (and type) of specific config values. Generally speaking contracts allow to describe more complex validations with depencecies between fields.
If you provide either validation option (or both) it will automatically be used to validate your config. If validation fails it will raise a Config::Validation::Error containing information about all the mismatches between the schema and your config.
Both examples below demonstrates how to ensure that the configuration has an optional email and the youtube structure with the api_key field filled. The contract adds an additional rule.
Leverage dry-validation, you can create a contract with a params schema and rules:
class ConfigContract < Dry::Validation::Contract
params do
optional(:email).maybe(:str?)
required(:youtube).schema do
required(:api_key).filled
end
end
rule(:email) do
unless /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i.match?(value)
key.failure('has invalid format')
end
end
end
Config.setup do |config|
config.validation_contract = ConfigContract.new
endThe above example adds a rule to ensure the email is valid by matching it against the provided regular expression.
Check dry-validation for more details.
You may
No open issues yet, or sync has not completed.