how to configure Sinatra to accept more option parameters?

53 Views Asked by At

I'm using Sinatra for a desktop app that runs on local host. When I start it up, I want to pass it an option like this ruby mysinatra.rb -first_name="My Name" However, I keep getting invalid option error. I think I'm getting it because Sinatra itself accepts options for things like port. For example, when I run ruby mysinatra.rb -h, the output I get (see below) is all the options that Sinatra accepts.

Note: The option that is going to be passed in is something that changes every time the application is going to be run, so it has to be convenient. It can't be hard-coded into a file.

This is the output from running ruby mysinatra.rb

Usage: main [options]
    -p port                          set the port (default is 4567)
    -s server                        specify rack server/handler
    -q                               turn on quiet mode (default is off)
    -x                               turn on the mutex lock (default is off)
    -e env                           set the environment (default is development)
    -o addr                          set the host (default is (env == 'development' ? 'localhost' : '0.0.0.0'))
1

There are 1 best solutions below

0
Casper On

Two ways to do this:

  1. Parse options before you require the Sinatra libraries. Make sure to remove any of your personal option strings from ARGV, so that regular Sinatra options still work (if that is your preference).

  2. Sinatra uses the Ruby optparse library for its own option processing. This library accepts a string -- to designate end of options. Therefore you could just do like this:

    ruby sinatra.rb -- --first_name="My Name"
    

    If you look at ARGV now, it would look like this:

    ["--", "--first_name=My Name"]
    

    From here you can do any ARGV option processing you like.