Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to new sinatra app

Tags:

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?

like image 573
Ronze Avatar asked Mar 11 '12 17:03

Ronze


2 Answers

  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)

like image 167
rnicholson Avatar answered Dec 28 '22 11:12

rnicholson


If you want to configure with params, I figured out that you could do this:

require 'sinatra/base'

class AwesomeApp < Sinatra::Base
  def initialize(app = nil, params = {})
    super(app)
    @bootstrap = params.fetch(:bootstrap, false)
  end
end
like image 25
Kasper Grubbe Avatar answered Dec 28 '22 12:12

Kasper Grubbe