Command Line Arguments with Sinatra - ruby

I have a Sinatra program that I am creating, and I would like to be able to pass in command line arguments to this app when I launch it. The problem that I have is that I'm not sure how to do this. I've tried Trollop and looked at OptParser. Trollop doesn't appear to work with Sinatra because OptParser seems to be "default" parser with Sinatra. Is this true? If so, how can I customize the types of arguments accepted when I launch my app?

ruby app.rb hello
# app.rb
require 'sinatra'
get '/' do
ARGV[0]
end
Now when I visit localhost:4567 (where Thin hosts my sinatra app), I see a page that says hello.

Alternatively, you can use environment variables.
Example borrowed from here: https://gist.github.com/benlovell/351962
require 'rubygems'
require 'sinatra'
get '/' do
ENV['envvar']
end
Then run:
envvar=something ruby app.rb

Related

Initializing an empty sinatra application

I am trying to create an empty Sinatra application with a config.ru file. Right now the only way I know how is to initialise it with cucumber but doing that creates extra files which I don't need including step definitions etc. When I run 'gem install Sinatra' in my working directory it says:
Successfully installed sinatra-1.4.5
Parsing documentation for sinatra-1.4.5
Done installing documentation for sinatra after 0 seconds
1 gem installed
Yet there is no config.ru file.
How do I initialise a Sinatra app so I have just the config.ru?
From the sinatra documentation
first create a file called app.rb in your working directory containing the following code:
require 'sinatra'
get '/' do
'Hello world!'
end
now create a file called config.ru with the following content:
require './app'
run Sinatra::Application
now run
rackup -p4567
to run the application

Rackup: cannot load such file 'sinatra'

I already installed sinatra gem and in irb, if I type,
require 'sinatra'
It returns true.
But when I do
rackup -d config.ru
It tells me
nil
Exception `LoadError' at /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:36 - cannot load such file -- sinatra
Here is my config.ru
require './app'
set :environment, ENV['RACK_ENV'].to_sym
set :app_file, 'app.rb'
disable :run
run Sinatra::Application
app.rb
require 'rubygems'
require 'sinatra'
get '' do
'Hello World'
end
I don't know what is going wrong.
$ which ruby
/usr/local/bin/ruby
$ which rackup
/usr/local/bin/rackup
$ ruby -v
ruby 1.9.3p374 (2013-01-15 revision 38858) [x86_64-linux]
$ rackup -v
Rack 1.2 (Release: 1.5)
I think this is just the verbose output from setting the -d option. Does the server actually start (after producing a load of output)?
What’s happening is this. Using -d sets Ruby’s $DEBUG flag to true. Rack then tries to load the app through the config.ru, which in turn loads your app.rb. The first thing in app.rb is require 'sinatra'.
Rubygems replaces the original require method with its own. When you call require it tries to load the file normally using the existing load path and the original require method. If the gem hasn’t been loaded this will raise a LoadError, which Rubygems catches before loading the gem.
With the $DEBUG flag set, Ruby will produce a message when an exception is raised even though it is rescued and dealt with, and this is what you’re seeing.
To avoid this simply omit the -d flag to your call to rackup (perhaps enabling warnings with -w would give you a sufficiently verbose output without swamping you in too much detail).
If the server isn’t starting then it will be a different issue rather than not finding Sinatra. If that is the case you’ll need to check the rest of the output for clues.
(Note that I originally thought something else was happening, and that’s what my questions int he comments were about.)
my guess is that your rackup script is a binstub of a 'rack' gem
installed in a diff ruby1.9x vm
maybe earlier version of ruby1.9.2
so it can't see the sinatra installed
I'd try 'which rackup' on the command line
This is definitely issue of load path. Anyway try to setup required ruby and gems via RVM and Bundler. It makes sure that Ruby interpreter and load paths are consistent.

Accessing the irb in a modular Sinatra application

I am building an application which subclasses Sinatra like so:
require 'rubygems'
require 'sinatra/base'
require 'sinatra/assetpack'
class App < Sinatra::Base
...
run!
end
How can I access irb? Options are not parsed when executing sinatra this way, how do I programmatically open an irb shell?
Just type as below (at the shell prompt):
irb -r ./my_app.rb
I'm a little confused whether you want to open an IRB session from within your app (?) or use IRB to debug your Sinatra project?
For debugging Rack-based apps (such as Sinatra), I like using the racksh gem, which "is like script/console in Rails" for Rack applications. Its main advantage over IRB is that racksh loads the entire application environment into the shell, making debugging a breeze.
From racksh's Github page: "It's purpose is to allow developer to introspect his application and/or make some initial setup. You can for example run DataMapper.auto_migrate! or make a request to /users/666 and check response details. It's mainly aimed at apps that don't have console-like component (ie. apps built with Sinatra) but all frameworks can benefit from interactive Rack stack and request introspection."
However, racksh requires your app to have a config.ru file, so you would have to re-write your app:
# in config.ru
require 'rubygems'
require 'sinatra/base'
require 'sinatra/assetpack'
require 'app.rb'
# in app.rb
class App < Sinatra::Base
...
run!
end
Then in your app folder (where config.ru resides):
$ gem install racksh # or add gem 'racksh' to your Gemfile and run bundle
$ racksh
Check this simple search interface for Microsoft's Bing using Sinatra and binger gem.
If you follow the instructions from there you will understand better.
First at all, create a Gemfile and add:
source "https://rubygems.org"
gem 'sinatra'
gem 'binger'
Then run the bundle command that will generated Gemfile.lock.
Then create a config.ru file, and add by example:
require 'rubygems'
require 'bundler'
Bundler.require
require './app.rb'
run MyApp
Your app.rb could look like this:
class MyApp < Sinatra::Base
get '/' do
#title = "Index"
erb:index
end
end
You must have a folder named views. Create index.erb and add:
< % = #title % >
Finally, run rackup.
Source: https://github.com/thinkphp/sinatra-bing
Demo: http://sinatra-bing.herokuapp.com/

Passenger Rack app 'cannot infer basepath'

I have a simple config.ru file for my Sinatra app.
require 'sinatra'
require 'app'
run Sinatra::Application
However, Passenger is failing with the error no such file to load -- app. I've tried using the 1.9 method require_relative but that now causes the error cannot infer basepath.
I'm currently using the very hacky require File.join(File.dirname(__FILE__), 'app' ), which is just horrible and I don't fancy doing that every time I want to require a file.
Is there any reason why Ruby isn't acting as usual?
In ruby 1.9.2 the current directory is no more in LOAD_PATH.
So what if your LOAD_PATH and add current_directory if is not made.

How to get Sinatra to auto-reload the file after each change?

I am using
# my_app.rb
load 'index.rb'
and start the sever like this
ruby my_app.rb
but it never reload any changes I made in index page.
Did I miss anything here?
See the Sinatra FAQ,
"How do I make my Sinatra app reload on changes?"
First off, in-process code reloading in Ruby is hard and having a
solution that works for every scenario is technically impossible.
Which is why we recommend you to do out-of-process reloading.
First you need to install rerun if you haven’t already:
$ gem install rerun
Now if you start your Sinatra app like this:
$ ruby app.rb
All you have to do for reloading is instead do this:
$ rerun 'ruby app.rb'
If you are for instance using rackup, instead do
the following:
$ rerun 'rackup'
You get the idea.
If you still want in-process reloading, check out Sinatra::Reloader.
gem install sinatra-reloader
require 'sinatra'
require 'sinatra/reloader'
Note: it will reload only sinatra handlers (and, maybe some sinatra server configuration commands), but not custom files, which you have to reload manually.
UPD after 9 years: seems like it is already possible to reload other files using also_reload, dont_reload and after_reload -- https://github.com/sinatra/sinatra/pull/1150
You can use the rerun gem.
gem install rerun
rerun 'ruby app.rb'
OR if you are using rackup
rerun 'rackup'
gem install sinatra-reloader
require 'sinatra/base'
require "sinatra/reloader"
class MyApp < Sinatra::Base
register Sinatra::Reloader
get '/' do
"Hello Testing1!"
end
end
You may want to set environment variable to development and conditionally load the gem.
When you run the application with Passenger Standalone, just create a tmp/always_restart file:
$ touch tmp/always_restart.txt
See Passenger documentation for more info.
I like the Shotgun gem. If you're using a modular Sinatra app and have a config.ru file it's easy to run.
shotgun config.ru
Check the gem out here. It's fairly straight forward and no configuration needed.
On Windows, I am using my restart gem for this:
restart ruby my_app.rb
or, with rackup:
restart rackup
See here for more info, hope you find it useful.
You could use guard-rack. Lifted from an article at dblock.org:
Add this to your Gemfile:
group :development do
gem "guard"
gem "guard-bundler"
gem "guard-rack"
end
Then, create a Guardfile at the root of your project with this content:
guard 'bundler' do
watch('Gemfile')
end
guard 'rack' do
watch('Gemfile.lock')
watch(%r{^(config|app|api)/.*})
end
Lastly, run Guard, like so: bundle exec guard, and rackup will reload every time.
If you only change your templates sinatra will always rerender them if you set your environment to development:
ruby app.rb -e development

Resources