jmolina
jmolina

Reputation: 269

Sinatra with multiple environment config

After working with Sinatra a couple of weeks I reached the moment to deploy my app in a staging environment. After reviewing sinatra configuration settings and looking around I did not find a way to have a config file per environment so that instead of having this:

require 'sinatra/base'
require 'sinatra/custom_logger'

class MyApp < Sinatra::Base
  helpers Sinatra::CustomLogger

  configure :development do
    logger = MyCustomLogger::Logger.new(param1, 
                                        param2, 
                                        param3,
                                        paramX)
    set :logger, logger
    ...
  end

  configure :production do
    logger = MyAnotherCustomerLogger.new(param1, param2)
    set :logger, logger
  end

  configure :whatever do

  end

  # endpoints definition
end

I would like to get to something cleaner like:

require 'sinatra/base'
require 'environment_config'

class MyApp < Sinatra::Base
  register EnvironmentConfig # Not sure how..

  ...
end

class EnvironmentConfig
  configuration :development do
    # 10 lines of configuration
  end

  configuration: production do
    # 20 lines of configuration
  end
end

And within that class/module we can either have a file per environment or one file with all the different configurations.

My question then would be, is there a way to structure a Sinatra app in a way that the configuration is not on the same place as the definitions of the endpoints? Thank you beforehand.

Upvotes: 0

Views: 855

Answers (2)

Antonio Cipolla
Antonio Cipolla

Reputation: 152

try sinatra/config, you can store all your config settings in a file and provide specific environment configuration.

require "sinatra"
require "sinatra/contrib"

config_file '../config/config.yml'

get "/"
  settings.bar
end

#config.yml
development:
  foo: development
  bar: bar
test:
  foo: test
  bar: bar
production:
  foo: production
  bar: bar

http://sinatrarb.com/contrib/config_file

Upvotes: 1

jmolina
jmolina

Reputation: 269

I finally came up with a solution using self.included class method:

# config.rb
require 'sinatra/custom_logger'

module Config
  def self.included(base_klass)
    base_klass.extend(ClassMethods)

    base_klass.helpers(Sinatra::CustomLogger)

    base_klass.class_eval do
      configure :development do
        logger = MyCustomLogger.new(
          param1,
          param2,
          param3,
          paramx
        )


        set :logger, logger
      end

      configure :production do
        # other stuff
      end
    end
  end

  module ClassMethods; end
end

then

require_relative 'config'

class MyApp < Sinatra::Base
  include Config

Upvotes: 1

Related Questions