Search code examples
rubysinatrarack

Pass arguments to new sinatra app


Simple question: I want to be able to pass options into my sinatra app in config.ru. How is that possible? My config.ru looks like this:

run MyApp

But I want to have this in my MyApp class to take arguments:

class MyApp < Sinatra::Base
  def initialize(config)
    @config = config
  end
end

But I can't figure out a way to do this. Ideas?


Solution

    1. Use set/settings

      require 'sinatra/base'
      
      class MyApp < Sinatra::Base
        get '/' do
          settings.time_at_startup.to_s
        end
      end
      
      # Just arbitrarily picking time as it'll be static but, diff for each run.
      MyApp.set :time_at_startup, Time.now
      
      run MyApp
      
    2. Use a config file. See Sinatra::ConfigFile in contrib (which also uses set and settings, but loads params from a YAML file)