This extension is part of the Sinatra::Contrib project. Run gem install sinatra-contrib to have it available.


Sinatra::ConfigFile is an extension that allows you to load the application's configuration from YAML files. It automatically detects if the files contains specific environment settings and it will use the corresponding to the current one.

You can access those options through settings within the application. If you try to get the value for a setting that hasn't been defined in the config file for the current environment, you will get whatever it was set to in the application.


Once you have written your configurations to a YAML file you can tell the extension to load them. See below for more information about how these files are interpreted.

For the examples, lets assume the following config.yml file:

greeting: Welcome to my file configurable application

Classic Application

require "sinatra"
require "sinatra/config_file"

config_file 'path/to/config.yml'

get '/' do
  @greeting = settings.greeting
  haml :index

# The rest of your classic application code goes here...

Modular Application

require "sinatra/base"
require "sinatra/config_file"

class MyApp < Sinatra::Base
  register Sinatra::ConfigFile

  config_file 'path/to/config.yml'

  get '/' do
    @greeting = settings.greeting
    haml :index

  # The rest of your modular application code goes here...

Config File Format

In its most simple form this file is just a key-value list:

foo: bar
something: 42
  a: 1
  b: 2

But it also can provide specific environment configuration. There are two ways to do that: at the file level and at the settings level.

At the settings level (e.g. in 'path/to/config.yml'):

  foo: development
  bar: bar
  foo: test
  bar: bar
  foo: production
  bar: bar

Or at the file level:

  development: development
  test: test
  production: production
bar: bar

In either case, will return the environment name, and will return "bar".

Be aware that if you have a different environment, besides development, test and production, you will also need to adjust the environments setting, otherwise the settings will not load. For instance, when you also have a staging environment:

set :environments, %w{development test production staging}

If you wish to provide defaults that may be shared among all the environments, this can be done by using one of the existing environments as the default using the YAML alias, and then overwriting values in the other environments:

development: &common_settings
  foo: 'foo'
  bar: 'bar'

  <<: *common_settings
  bar: 'baz' # override the default value
Fork me on GitHub