Application Configuration Blocks

We’ve seen how to map routes to actions (blocks of code). And how actions do specific things that return information back to a user. Sometimes these actions need to know more than just the parameters which have been passed. And sometimes, some information might need to be shared across multiple actions.

For example:

  • If we were building a shopping application, we might want several actions to know what the maximum number of items you can have in your cart
  • If we’re building a bot that’s going to need to access a third party service like Twitter, we might want to make the access information available to all our routes
  • If we’re going to send emails from our application, we might want to store the address and information to send them from.

We can use the configuration block in Sinatra to hold settings or other information we might want to make available to multiple routes. This information is simple stuff we need to know and stuff that won’t change anytime soon. It shouldn’t make sense to store in a relational database either.

The configuration block is run once as our web application launches for the first time and can be set up like this:

configure do
  # setting one option
  set :option, 'value'

  # same as `set :option, true`
  enable :option

  # same as `set :option, false`
  disable :option


Then you can access this information in any route using settings

configure do
  # setting one option
  set :application_title, 'My Application Name'

get '/' do
  # check if the setting exists and is set
  # get the application title and return it 
  settings.application_title  # => 'My Application Name'


The latest tutorials sent straight to your inbox.