sinatra config.ru: what is the configure block for?

Markus picture Markus · Jan 19, 2013 · Viewed 9.2k times · Source

I'm using Sinatra with Apache and Phusion-Passenger with "classic" style:

# config.ru
require 'sinatra'

configure do
    ....
end

require './app'

run Sinatra::Application

I want to define some things. What is the difference between defining it inside the configure block or outside?

# config.ru
require 'sinatra'

# A) Defining logger here
rack = File.new("logs/rack.log", "a+") 
use Rack::CommonLogger, rack

# B) Global variables here
LOGGER = Logger.new(...)

# C) Gem configuration here
DataMapper::Property::Boolean.allow_nil(false)

configure do
    # A) Or defining logger here?
    rack = File.new("logs/rack.log", "a+") 
    use Rack::CommonLogger, rack

    # B) Or global variables here?
    LOGGER = Logger.new(...)

    # C) Or gem configuration here?
    DataMapper::Property::Boolean.allow_nil(false)
    ....
end

require './app'

run Sinatra::Application

Are there some general rules what should be done outside and what should be done inside? What is the difference? I tested both variants, and both seemed to work equally well.

I know configure can be used to react on environment like this:

configure :development do
    ....
end

So it is useful for different environment configurations. This use case is clear, but what about general configurations for every environment? Where do I put them? Is this only a matter of style?

Answer

three picture three · Jan 19, 2013

This is in the first place a matter of environments and in the second place a matter of style. There is no difference where you put your configurations.

It does make your code a lot more readable (IMHO) if you put it into a block. Also it will let you add environment based options which you then put into their own respective blocks.

To sum it up, it's up to you :)