Skip to content
Browse files

convert code blocks to fenced code for syntax highlighting, removed s…

…ome whitespace
  • Loading branch information...
1 parent ebfbf9a commit 35c519ec0da33bf8139e1b5314676cb7ed4597f8 @zzak zzak committed
View
156 databases/mongo.md
@@ -15,102 +15,114 @@ available.
The first step is in connecting your application to an instance of Mongo is
to create a connection. You can do this in your _configure_ block:
- require 'rubygems'
- require 'sinatra'
- require 'mongo'
- require 'json' # required for .to_json
-
- configure do
- conn = Mongo::Connection.new("localhost", 27017)
- set :mongo_connection, conn
- set :mongo_db, conn.db('test')
- end
+```ruby
+require 'rubygems'
+require 'sinatra'
+require 'mongo'
+require 'json' # required for .to_json
+
+configure do
+ conn = Mongo::Connection.new("localhost", 27017)
+ set :mongo_connection, conn
+ set :mongo_db, conn.db('test')
+end
+```
With a connection "in hand" you can connect to any database and collection in
your Mongo instance.
- get '/collections/?' do
- settings.mongo_db.collection_names
- end
-
- helpers do
- # a helper method to turn a string ID
- # representation into a BSON::ObjectId
- def object_id val
- BSON::ObjectId.from_string(val)
- end
-
- def document_by_id id
- id = object_id(id) if String === id
- settings.mongo_db['test'].
- find_one(:_id => id).to_json
- end
- end
+```ruby
+get '/collections/?' do
+ settings.mongo_db.collection_names
+end
+
+helpers do
+ # a helper method to turn a string ID
+ # representation into a BSON::ObjectId
+ def object_id val
+ BSON::ObjectId.from_string(val)
+ end
+
+ def document_by_id id
+ id = object_id(id) if String === id
+ settings.mongo_db['test'].
+ find_one(:_id => id).to_json
+ end
+end
+```
<span style='font-size: smaller'>([top](#top))</span>
<a name='find' />
###Finding Records###
- # list all documents in the test collection
- get '/documents/?' do
- content_type :json
- settings.mongo_db['test'].find.to_a.to_json
- end
-
- # find a document by its ID
- get '/document/:id/?' do
- content_type :json
- document_by_id(params[:id]).to_json
- end
+```ruby
+# list all documents in the test collection
+get '/documents/?' do
+ content_type :json
+ settings.mongo_db['test'].find.to_a.to_json
+end
+
+# find a document by its ID
+get '/document/:id/?' do
+ content_type :json
+ document_by_id(params[:id]).to_json
+end
+```
<span style='font-size: smaller'>([top](#top))</span>
<a name='insert' />
###Inserting Records###
- # insert a new document from the request parameters,
- # then return the full document
- post '/new_document/?' do
- content_type :json
- new_id = settings.mongo_db['test'].insert params
- document_by_id(new_id).to_json
- end
+```ruby
+# insert a new document from the request parameters,
+# then return the full document
+post '/new_document/?' do
+ content_type :json
+ new_id = settings.mongo_db['test'].insert params
+ document_by_id(new_id).to_json
+end
+```
<span style='font-size: smaller'>([top](#top))</span>
<a name='update' />
###Updating Records###
- # update the document specified by :id, setting its
- # contents to params, then return the full document
- put '/update/:id/?' do
- content_type :json
- id = object_id(params[:id])
- settings.mongo_db['test'].update(:_id => id, params)
- document_by_id(id).to_json
- end
-
- # update the document specified by :id, setting just its
- # name attribute to params[:name], then return the full
- # document
- put '/update_name/:id/?' do
- content_type :json
- id = object_id(params[:id])
- name = params[:name]
- settings.mongo_db['test'].
- update(:_id => id, {"$set" => {:name => name}})
- document_by_id(id).to_json
- end
+```ruby
+# update the document specified by :id, setting its
+# contents to params, then return the full document
+put '/update/:id/?' do
+ content_type :json
+ id = object_id(params[:id])
+ settings.mongo_db['test'].update(:_id => id, params)
+ document_by_id(id).to_json
+end
+
+# update the document specified by :id, setting just its
+# name attribute to params[:name], then return the full
+# document
+put '/update_name/:id/?' do
+ content_type :json
+ id = object_id(params[:id])
+ name = params[:name]
+ settings.mongo_db['test'].
+ update(:_id => id, {"$set" => {:name => name}})
+ document_by_id(id).to_json
+end
+```
<span style='font-size: smaller'>([top](#top))</span>
<a name='delete' />
###Deleting Records###
- # delete the specified document and return success
- delete '/remove/:id' do
- content_type :json
- settings.mongo_db['test'].
- remove(:_id => object_id(params[:id]))
- {:success => true}.to_json
- end
+```ruby
+# delete the specified document and return success
+delete '/remove/:id' do
+ content_type :json
+ settings.mongo_db['test'].
+ remove(:_id => object_id(params[:id]))
+ {:success => true}.to_json
+end
+```
<span style='font-size: smaller'>([top](#top))</span>
For more information on using the Ruby driver without an ORM take a look at [MongoDB's tutorial][rubydrivertutorial].
View
56 deployment/apache_with_passenger.md
@@ -19,11 +19,15 @@ You have a number of options when [installing phusion
passenger](http://modrails.com/documentation/Users%20guide%20Apache.html#_installing_upgrading_and_uninstalling_phusion_passenger),
however the gem is likely the easiest way to get started.
- gem install passenger
+```bash
+gem install passenger
+```
Once you've got that installed you can build the passenger apache module.
- passenger-install-apache2-module
+```bash
+passenger-install-apache2-module
+```
Follow the instructions given by the installer.
@@ -37,9 +41,11 @@ the `tmp` and `public` sub-directories of your application.
In order to fit these prerequisites, simply make sure you have the following
setup:
- mkdir public
- mkdir tmp
- config.ru
+```bash
+mkdir public
+mkdir tmp
+config.ru
+```
The public directory is for serving static files and tmp directory is for the
`restart.txt` application restart mechanism. `config.ru` is where you will
@@ -50,25 +56,29 @@ place your rackup configuration.
Once you have these directories in place, you can setup your applications
rackup file, `config.ru`.
- require 'rubygems'
- require 'sinatra'
- require File.expand_path '../app.rb', __FILE__
+```ruby
+require 'rubygems'
+require 'sinatra'
+require File.expand_path '../app.rb', __FILE__
- run Sinatra::Application
+run Sinatra::Application
+```
**Virtual Host**
Next thing you'll have to do is setup the [Apache Virtual
Host](http://httpd.apache.org/docs/2.2/vhosts/) for your app.
- <VirtualHost *:80>
- ServerName www.yourapplication.com
- DocumentRoot /path/to/app/public
- <Directory /path/to/app/public>
- Allow from all
- Options -MultiViews
- </Directory>
- </VirtualHost>
+```bash
+<VirtualHost *:80>
+ ServerName www.yourapplication.com
+ DocumentRoot /path/to/app/public
+ <Directory /path/to/app/public>
+ Allow from all
+ Options -MultiViews
+ </Directory>
+</VirtualHost>
+```
That should just about do it for your basic apache and passenger configuration.
For more specific information please visit the [official modrails
@@ -81,9 +91,11 @@ Apache](http://httpd.apache.org/docs/2.2/stopping.html).
On most debian-based systems you should be able to:
- sudo apache2ctl stop
- # then
- sudo apache2ctl start
+```bash
+sudo apache2ctl stop
+# then
+sudo apache2ctl start
+```
To restart Apache. Check the link above for more detailed information.
@@ -91,7 +103,9 @@ In order to [restart the Passenger
application](http://www.modrails.com/documentation/Users%20guide%20Apache.html#_redeploying_restarting_the_ruby_on_rails_application),
all you need to do is run this simple command for your application root:
- touch tmp/restart.txt
+```bash
+touch tmp/restart.txt
+```
You should be up and running now with [Phusion Passenger](http://modrails.com/)
and [Apache](http://httpd.apache.org/), if you run into any problems please
View
88 deployment/dreamhost_via_passenger.md
@@ -4,41 +4,51 @@ Dreamhost Deployment via Passenger
You can deploy your Sinatra apps to Dreamhost, a shared web hosting service,
via Passenger with relative ease. Here's how.
-1. Setting up the account in the Dreamhost interface
-
- Domains -> Manage Domains -> Edit (web hosting column)
- Enable 'Ruby on Rails Passenger (mod_rails)'
- Add the public directory to the web directory box. So if you were using 'rails.com', it would change to 'rails.com/public'
- Save your changes
-
-2. Creating the directory structure
-
- domain.com/
- domain.com/tmp
- domain.com/public
- # a vendored version of sinatra - not necessary if you use the gem
- domain.com/sinatra
-
-3. Here is an example config.ru file that does two things. First, it requires
- your main app file, whatever it's called. In the example, it will look for
- `myapp.rb`. Second, run your application. If you're subclassing, use the
- subclass's name, otherwise use Sinatra::Application.
-
- require File.expand_path '../myapp.rb', __FILE__
-
- run Sinatra::Application
-
-4. A very simple Sinatra application
-
- # this is myapp.rb referred to above
- require 'sinatra'
- get '/' do
- "Worked on dreamhost"
- end
-
- get '/foo/:bar' do
- "You asked for foo/#{params[:bar]}"
- end
+### Setting up the account in the Dreamhost interface
+
+```
+Domains -> Manage Domains -> Edit (web hosting column)
+Enable 'Ruby on Rails Passenger (mod_rails)'
+Add the public directory to the web directory box. So if you were using 'rails.com', it would change to 'rails.com/public'
+Save your changes
+```
+
+### Creating the directory structure
+
+```
+domain.com/
+domain.com/tmp
+domain.com/public
+# a vendored version of sinatra - not necessary if you use the gem
+domain.com/sinatra
+```
+
+### Rack integration
+
+Here is an example config.ru file that does two things. First, it requires
+your main app file, whatever it's called. In the example, it will look for
+`myapp.rb`. Second, run your application. If you're subclassing, use the
+subclass's name, otherwise use Sinatra::Application.
+
+```ruby
+require File.expand_path '../myapp.rb', __FILE__
+
+run Sinatra::Application
+```
+
+### A very simple Sinatra application
+
+```ruby
+# this is myapp.rb referred to above
+require 'sinatra'
+get '/' do
+ "Worked on dreamhost"
+end
+
+get '/foo/:bar' do
+ "You asked for foo/#{params[:bar]}"
+end
+```
And that's all there is to it! Once it's all setup, point your browser at your
domain, and you should see a 'Worked on Dreamhost' page. To restart the
@@ -54,7 +64,9 @@ already activated rack-0.4.0". This happens because DreamHost has version 0.4.0
installed, when recent versions of Sinatra require more recent versions of Rack.
The solution is to explicitly require the rack and sinatra gems in your
config.ru. Add the following two lines to the start of your config.ru file:
-
- require '/home/USERNAME/.gem/ruby/1.8/gems/rack-VERSION-OF-RACK-GEM-YOU-HAVE-INSTALLELD/lib/rack.rb'
- require '/home/USERNAME/.gem/ruby/1.8/gems/sinatra-VERSION-OF-SINATRA-GEM-YOU-HAVE-INSTALLELD/lib/sinatra.rb'
+
+```ruby
+require '/home/USERNAME/.gem/ruby/1.8/gems/rack-VERSION-OF-RACK-GEM-YOU-HAVE-INSTALLELD/lib/rack.rb'
+require '/home/USERNAME/.gem/ruby/1.8/gems/sinatra-VERSION-OF-SINATRA-GEM-YOU-HAVE-INSTALLELD/lib/sinatra.rb'
+```
View
113 deployment/fastcgi.md
@@ -12,63 +12,70 @@ Luckily, Rack supports various connectors, including CGI and FastCGI. Unluckily
for us, FastCGI doesn't quite work with the current Sinatra release without some tweaking.
### Deployment with Sinatra version 0.9
+
From version 0.9.0 Sinatra requires Rack 0.9.1, however FastCGI wrapper from
this version seems not working well with Sinatra unless you define your
application as a subclass of Sinatra::Application class and run this
application directly as a Rack application.
Steps to deploy via FastCGI:
-* htaccess
-* subclass your application as Sinatra::Application
-* dispatch.fcgi
-
-1. .htaccess
-
- RewriteEngine on
-
- AddHandler fastcgi-script .fcgi
- Options +FollowSymLinks +ExecCGI
-
- RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
-
-2. Subclass your application as Sinatra::Application
-
- # my_sinatra_app.rb
- class MySinatraApp < Sinatra::Application
- # your sinatra application definitions
- end
-
-
-3. dispatch.fcgi - Run this application directly as a Rack application
-
- #!/usr/local/bin/ruby
-
- require 'rubygems'
- require 'rack'
-
- fastcgi_log = File.open("fastcgi.log", "a")
- STDOUT.reopen fastcgi_log
- STDERR.reopen fastcgi_log
- STDOUT.sync = true
-
- module Rack
- class Request
- def path_info
- @env["REDIRECT_URL"].to_s
- end
- def path_info=(s)
- @env["REDIRECT_URL"] = s.to_s
- end
- end
- end
-
- load 'my\_sinatra\_app.rb'
-
- builder = Rack::Builder.new do
- map '/' do
- run MySinatraApp.new
- end
- end
-
- Rack::Handler::FastCGI.run(builder)
+
+ * htaccess
+ * subclass your application as Sinatra::Application
+ * dispatch.fcgi
+
+### .htaccess
+
+```
+RewriteEngine on
+
+AddHandler fastcgi-script .fcgi
+Options +FollowSymLinks +ExecCGI
+
+RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
+```
+
+### Subclass your application as Sinatra::Application
+
+```ruby
+# my_sinatra_app.rb
+class MySinatraApp < Sinatra::Application
+ # your sinatra application definitions
+end
+```
+
+### dispatch.fcgi - Run this application directly as a Rack application
+
+```ruby
+#!/usr/local/bin/ruby
+
+require 'rubygems'
+require 'rack'
+
+fastcgi_log = File.open("fastcgi.log", "a")
+STDOUT.reopen fastcgi_log
+STDERR.reopen fastcgi_log
+STDOUT.sync = true
+
+module Rack
+ class Request
+ def path_info
+ @env["REDIRECT_URL"].to_s
+ end
+ def path_info=(s)
+ @env["REDIRECT_URL"] = s.to_s
+ end
+ end
+end
+
+load 'my\_sinatra\_app.rb'
+
+builder = Rack::Builder.new do
+ map '/' do
+ run MySinatraApp.new
+ end
+end
+
+Rack::Handler::FastCGI.run(builder)
+```
View
92 deployment/jruby.md
@@ -20,44 +20,54 @@ There are several ways to install [JRuby][jruby], but that is beyond the scope
of this article. For now, we will assume you are using the excellent [RVM][rvm]
, from Wayne Seguin, and proceed from there.
- rvm install jruby # (if you haven't already)
- rvm use jruby
- gem install mongrel
+```bash
+rvm install jruby # (if you haven't already)
+rvm use jruby
+gem install mongrel
+```
Create a classic Sinatra application and save it to hello.rb:
- require 'rubygems'
- require 'sinatra'
-
- get '/' do
- %Q{
- <html>
- <body>
- Hello from the
- <strong>wonderful</strong>
- world of JRuby!
- </body>
- </html>
- }
- end
+```ruby
+require 'rubygems'
+require 'sinatra'
+
+get '/' do
+ %Q{
+ <html>
+ <body>
+ Hello from the
+ <strong>wonderful</strong>
+ world of JRuby!
+ </body>
+ </html>
+ }
+end
+```
Now, you're ready to fire it up.
- ruby /path/to/hello.rb
+```
+ruby /path/to/hello.rb
+```
That's it. Open <http://localhost:4567> in your browser and your Sinatra
application should greet you from the **wonderful** world of [JRuby][jruby].
Of course, you can use a config.ru and rackup as well:
- cat <<EOF>config.ru
- require 'rubygems'
- require 'sinatra'
- require File.expand_path '../hello.rb', __FILE__
- run Sinatra::Application
- EOF
-
- rackup config.ru
+```ruby
+require 'rubygems'
+require 'sinatra'
+require File.expand_path '../hello.rb', __FILE__
+run Sinatra::Application
+```
+
+Then launch app with the following command:
+
+```bash
+rackup config.ru
+```
Now go to <http://localhost:9292> and you'll see the same **wonderful** greeting.
@@ -68,8 +78,10 @@ application within an embedded Apache Tomcat container.
Again, with our example above, you would do the following:
- gem install trinidad
- trinidad -r config.ru -p 4567 -g ERROR
+```bash
+gem install trinidad
+trinidad -r config.ru -p 4567 -g ERROR
+```
The _-g_ option sets the logging level to error.
@@ -89,27 +101,39 @@ For installation help checkout
During the installation of [TorqueBox][TorqueBox] you probably set a JBOSS_HOME
variable, if not make sure you have set it like this:
- export JBOSS_HOME=/path/to/TorqueBox/jboss
+```bash
+export JBOSS_HOME=/path/to/TorqueBox/jboss
+```
In your Rakefile add this line:
- require 'TorqueBox/tasks'
+```ruby
+require 'TorqueBox/tasks'
+```
Now, you are ready to deploy your application:
- rake TorqueBox:deploy
+```bash
+rake TorqueBox:deploy
+```
To deploy a production version of your application:
- RACK_ENV=production rake TorqueBox:deploy
+```bash
+RACK_ENV=production rake TorqueBox:deploy
+```
To take your application down, you run:
- rake TorqueBox:undeploy
+```bash
+rake TorqueBox:undeploy
+```
[TorqueBox][TorqueBox] also allows you deploy to a non-root context:
- rake TorqueBox:deploy['/hello']
+```bash
+rake TorqueBox:deploy['/hello']
+```
## Conclusion
View
143 deployment/lighttpd_proxied_to_thin.md
@@ -4,58 +4,65 @@ Lighttpd Proxied to Thin
This will cover how to deploy Sinatra to a load balanced reverse
proxy setup using Lighttpd and Thin.
-1. Install Lighttpd and Thin
-
- # Figure out lighttpd yourself, it should be handled by your
- # linux distro's package manager
-
- # For thin:
- gem install thin
-
-2. Create your rackup file -- the `require 'app'` line should require the actual
- Sinatra app you have written.
-
- ## This is not needed for Thin > 1.0.0
- ENV['RACK_ENV'] = "production"
-
- require File.expand_path '../app.rb', __FILE__
-
- run Sinatra::Application
-
-3. Setup a config.yml - change the /path/to/my/app path to reflect reality.
-
- ---
- environment: production
- chdir: /path/to/my/app
- address: 127.0.0.1
- user: root
- group: root
- port: 4567
- pid: /path/to/my/app/thin.pid
- rackup: /path/to/my/app/config.ru
- log: /path/to/my/app/thin.log
- max_conns: 1024
- timeout: 30
- max_persistent_conns: 512
- daemonize: true
-
-4. Setup lighttpd.conf - change mydomain to reflect reality. Also make
- sure the first port here matches up with the port setting in config.yml.
-
- $HTTP["host"] =~ "(www\.)?mydomain\.com" {
- proxy.balance = "fair"
- proxy.server = ("/" =>
- (
- ( "host" => "127.0.0.1", "port" => 4567 ),
- ( "host" => "127.0.0.1", "port" => 4568 )
- )
- )
- }
-
-5. Start thin and your application. I have a rake script so I can just
- call "rake start" rather than typing this in.
-
- thin -s 2 -C config.yml -R config.ru start
+### Install Lighttpd and Thin
+
+```bash
+# Figure out lighttpd yourself, it should be handled by your
+# linux distro's package manager
+
+# For thin:
+gem install thin
+```
+
+### Create your rackup file -- the `require 'app'` line should require the actual Sinatra app you have written.
+
+```ruby
+## This is not needed for Thin > 1.0.0
+ENV['RACK_ENV'] = "production"
+
+require File.expand_path '../app.rb', __FILE__
+
+run Sinatra::Application
+```
+
+### Setup a config.yml - change the /path/to/my/app path to reflect reality.
+
+```yaml
+---
+ environment: production
+ chdir: /path/to/my/app
+ address: 127.0.0.1
+ user: root
+ group: root
+ port: 4567
+ pid: /path/to/my/app/thin.pid
+ rackup: /path/to/my/app/config.ru
+ log: /path/to/my/app/thin.log
+ max_conns: 1024
+ timeout: 30
+ max_persistent_conns: 512
+ daemonize: true
+```
+
+### Setup lighttpd.conf - change mydomain to reflect reality. Also make sure the first port here matches up with the port setting in config.yml.
+
+```
+$HTTP["host"] =~ "(www\.)?mydomain\.com" {
+ proxy.balance = "fair"
+ proxy.server = ("/" =>
+ (
+ ( "host" => "127.0.0.1", "port" => 4567 ),
+ ( "host" => "127.0.0.1", "port" => 4568 )
+ )
+ )
+}
+```
+
+### Start thin and your application. I have a rake script so I can just call "rake start" rather than typing this in.
+
+```bash
+thin -s 2 -C config.yml -R config.ru start
+```
You're done! Go to mydomain.com/ and see the result! Everything should be setup
now, check it out at the domain you setup in your lighttpd.conf file.
@@ -63,21 +70,23 @@ now, check it out at the domain you setup in your lighttpd.conf file.
*Variation* - nginx via proxy - The same approach to proxying can be applied to
the nginx web server
- upstream www_mydomain_com {
- server 127.0.0.1:5000;
- server 127.0.0.1:5001;
- }
-
- server {
- listen www.mydomain.com:80
- server_name www.mydomain.com live;
- access_log /path/to/logfile.log
-
- location / {
- proxy_pass http://www_mydomain_com;
- }
-
- }
+```
+upstream www_mydomain_com {
+ server 127.0.0.1:5000;
+ server 127.0.0.1:5001;
+}
+
+server {
+ listen www.mydomain.com:80
+ server_name www.mydomain.com live;
+ access_log /path/to/logfile.log
+
+ location / {
+ proxy_pass http://www_mydomain_com;
+ }
+
+}
+```
*Variation* - More Thin instances - To add more thin instances, change the
`-s 2` parameter on the thin start command to be how ever many servers you want.
View
230 deployment/nginx_proxied_to_unicorn.md
@@ -14,7 +14,9 @@ For more information on installing nginx, check [the official docs](http://wiki.
Once you have nginx installed, you can install unicorn with rubygems:
- gem install unicorn
+```
+gem install unicorn
+```
Now that's done we can setup a basic Rack application in Sinatra.
@@ -23,26 +25,30 @@ Now that's done we can setup a basic Rack application in Sinatra.
To start our example application, let's first create a `config.ru` in our
application root.
- require "rubygems"
- require "sinatra"
+```ruby
+require "rubygems"
+require "sinatra"
- require File.expand_path '../myapp.rb', __FILE__
+require File.expand_path '../myapp.rb', __FILE__
- run MyApp
+run MyApp
+```
Let's now use the `myapp.rb` that we specified in our Rack config file as our
Sinatra application.
- require "rubygems"
- require "sinatra/base"
+```ruby
+require "rubygems"
+require "sinatra/base"
- class MyApp < Sinatra::Base
+class MyApp < Sinatra::Base
- get '/' do
- 'Hello, nginx and unicorn!'
- end
+ get '/' do
+ 'Hello, nginx and unicorn!'
+ end
- end
+end
+```
Now that we have our application in place, let's get on to configuring our
proxy.
@@ -59,32 +65,36 @@ Configuring unicorn is really easy and provides an easy to use Ruby DSL for
doing so. In our application's root we'll first need to make a couple
directories, if you haven't already:
- mkdir tmp
- mkdir tmp/sockets
- mkdir tmp/pids
- mkdir log
+```
+mkdir tmp
+mkdir tmp/sockets
+mkdir tmp/pids
+mkdir log
+```
Once those are in place, we're ready to setup our `unicorn.rb` configuration.
- # set path to app that will be used to configure unicorn,
- # note the trailing slash in this example
- @dir = "/path/to/app/"
+```ruby
+# set path to app that will be used to configure unicorn,
+# note the trailing slash in this example
+@dir = "/path/to/app/"
- worker_processes 2
- working_directory @dir
+worker_processes 2
+working_directory @dir
- timeout 30
+timeout 30
- # Specify path to socket unicorn listens to,
- # we will use this in our nginx.conf later
- listen "#{@dir}tmp/sockets/unicorn.sock", :backlog => 64
+# Specify path to socket unicorn listens to,
+# we will use this in our nginx.conf later
+listen "#{@dir}tmp/sockets/unicorn.sock", :backlog => 64
- # Set process id path
- pid "#{@dir}tmp/pids/unicorn.pid"
+# Set process id path
+pid "#{@dir}tmp/pids/unicorn.pid"
- # Set log file paths
- stderr_path "#{@dir}log/unicorn.stderr.log"
- stdout_path "#{@dir}log/unicorn.stdout.log"
+# Set log file paths
+stderr_path "#{@dir}log/unicorn.stderr.log"
+stdout_path "#{@dir}log/unicorn.stdout.log"
+```
As you can see, unicorn is extremely simple to setup. Let's move onto nginx
now, soon enough you'll be well on your way to serving up all kinds of great
@@ -101,78 +111,80 @@ some of the configuration out into `sites-enabled` and other nginx conventions.
However, for most common and simple implementations this guide should do the
trick.
- # this sets the user nginx will run as,
- #and the number of worker processes
- user nobody nogroup;
- worker_processes 1;
-
- # setup where nginx will log errors to
- # and where the nginx process id resides
- error_log /var/log/nginx/error.log;
- pid /var/run/nginx.pid;
-
- events {
- worker_connections 1024;
- # set to on if you have more than 1 worker_processes
- accept_mutex off;
+```bash
+# this sets the user nginx will run as,
+#and the number of worker processes
+user nobody nogroup;
+worker_processes 1;
+
+# setup where nginx will log errors to
+# and where the nginx process id resides
+error_log /var/log/nginx/error.log;
+pid /var/run/nginx.pid;
+
+events {
+ worker_connections 1024;
+ # set to on if you have more than 1 worker_processes
+ accept_mutex off;
+}
+
+http {
+ include /etc/nginx/mime.types;
+
+ default_type application/octet-stream;
+ access_log /tmp/nginx.access.log combined;
+
+ # use the kernel sendfile
+ sendfile on;
+ # prepend http headers before sendfile()
+ tcp_nopush on;
+
+ keepalive_timeout 5;
+ tcp_nodelay on;
+
+ gzip on;
+ gzip_vary on;
+ gzip_min_length 500;
+
+ gzip_disable "MSIE [1-6]\.(?!.*SV1)";
+ gzip_types text/plain text/xml text/css
+ text/comma-separated-values
+ text/javascript application/x-javascript
+ application/atom+xml image/x-icon;
+
+ # use the socket we configured in our unicorn.rb
+ upstream unicorn_server {
+ server unix:/path/to/app/tmp/sockets/unicorn.sock
+ fail_timeout=0;
+ }
+
+ # configure the virtual host
+ server {
+ # replace with your domain name
+ server_name my-sinatra-app.com;
+ # replace this with your static Sinatra app files, root + public
+ root /path/to/app/public;
+ # port to listen for requests on
+ listen 80;
+ # maximum accepted body size of client request
+ client_max_body_size 4G;
+ # the server will close connections after this time
+ keepalive_timeout 5;
+
+ location / {
+ try_files $uri @app;
}
- http {
- include /etc/nginx/mime.types;
-
- default_type application/octet-stream;
- access_log /tmp/nginx.access.log combined;
-
- # use the kernel sendfile
- sendfile on;
- # prepend http headers before sendfile()
- tcp_nopush on;
-
- keepalive_timeout 5;
- tcp_nodelay on;
-
- gzip on;
- gzip_vary on;
- gzip_min_length 500;
-
- gzip_disable "MSIE [1-6]\.(?!.*SV1)";
- gzip_types text/plain text/xml text/css
- text/comma-separated-values
- text/javascript application/x-javascript
- application/atom+xml image/x-icon;
-
- # use the socket we configured in our unicorn.rb
- upstream unicorn_server {
- server unix:/path/to/app/tmp/sockets/unicorn.sock
- fail_timeout=0;
- }
-
- # configure the virtual host
- server {
- # replace with your domain name
- server_name my-sinatra-app.com;
- # replace this with your static Sinatra app files, root + public
- root /path/to/app/public;
- # port to listen for requests on
- listen 80;
- # maximum accepted body size of client request
- client_max_body_size 4G;
- # the server will close connections after this time
- keepalive_timeout 5;
-
- location / {
- try_files $uri @app;
- }
-
- location @app {
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header Host $http_host;
- proxy_redirect off;
- # pass to the upstream unicorn server mentioned above
- proxy_pass http://unicorn_server;
- }
- }
+ location @app {
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header Host $http_host;
+ proxy_redirect off;
+ # pass to the upstream unicorn server mentioned above
+ proxy_pass http://unicorn_server;
}
+ }
+}
+```
Once you replace `path/to/app` with the location to your Sinatra application,
you should be able now start your application and web server.
@@ -181,7 +193,9 @@ you should be able now start your application and web server.
First thing you will need to do is boot up the unicorn processes:
- unicorn -c path/to/unicorn.rb -E development -D -l 0.0.0.0:3001
+```bash
+unicorn -c path/to/unicorn.rb -E development -D -l 0.0.0.0:3001
+```
It's important to note the flags here, `-c` is path to your unicorn
configuration. `-E` is the Rack environment for your application to run under.
@@ -191,7 +205,9 @@ listen to.
Lastly, let's start up nginx. On most debian-based systems you can use the following
command:
- /etc/init.d/nginx start
+```bash
+/etc/init.d/nginx start
+```
However, you should check with your distribution as to where the nginx daemon
resides.
@@ -206,12 +222,16 @@ asking yourself: How do I stop this thing?
Here's how:
- $ ps -ax | grep unicorn
+```bash
+$ ps -ax | grep unicorn
+```
This will output the processes running unicorn, in the first column should be
the process id (pid). In order to stop unicorn in it's tracks:
- kill -9 <PID>
+```bash
+kill -9 <PID>
+```
There should be a `master` process which once that is killed, the
workers should follow. Feel free to search the processes again to make sure
@@ -220,7 +240,9 @@ they've all stopped before restarting.
To stop nginx you can use a similar technique as above, or if you've got the
nginx init scripts installed on any debian-based system use:
- sudo /etc/init.d/nginx stop
+```bash
+sudo /etc/init.d/nginx stop
+```
That should wrap things up for deploying nginx and unicorn, for more
information on stopping the server look into `man ps` and `man kill`.
View
118 development/bundler.md
@@ -22,36 +22,40 @@ In most cases you're going to require gems from the [official rubygems
repository](http://rubygems.org/). Here's an example Gemfile for an application
that uses Sinatra as a main dependency and RSpec for testing:
- # define our source to loook for gems
- source "http://rubygems.org/"
+```ruby
+# define our source to loook for gems
+source "http://rubygems.org/"
- # declare the sinatra dependency
- gem "sinatra"
+# declare the sinatra dependency
+gem "sinatra"
- # setup our test group and require rspec
- group :test do
- gem "rspec"
- end
+# setup our test group and require rspec
+group :test do
+ gem "rspec"
+end
- # require a relative gem version
- gem "i18n", "~> 0.4.1"
+# require a relative gem version
+gem "i18n", "~> 0.4.1"
+```
**Git**
Bundler also supports the installation of gems through git, so long as the
repository contains a valid gemspec for the gem you're trying to install.
- # lets use sinatra edge
- gem "sinatra", :git => "http://github.com/sinatra/sinatra.git"
+```ruby
+# lets use sinatra edge
+gem "sinatra", :git => "http://github.com/sinatra/sinatra.git"
- # and lets we use the rspec 2.0 release candidate from git
- group :test do
- gem "rspec", :git => "http://github.com/rspec/rspec.git",
- :tag => "v2.0.0.rc"
- end
+# and lets we use the rspec 2.0 release candidate from git
+group :test do
+ gem "rspec", :git => "http://github.com/rspec/rspec.git",
+ :tag => "v2.0.0.rc"
+end
- # as well as i18n from git
- gem "i18n", :git => "http://github.com/svenfuchs/i18n.git"
+# as well as i18n from git
+gem "i18n", :git => "http://github.com/svenfuchs/i18n.git"
+```
### Commands (CLI)
@@ -61,20 +65,30 @@ commands.
**Installing**
- # Install specified gems from your Gemfile and Gemfile.lock
- bundle install
-
- # Inspect your bundle to see if you've met your applications requirements
- bundle check
+```bash
+# Install specified gems from your Gemfile and Gemfile.lock
+bundle install
+```
- # List all gems in your bundle
- bundle list
+```bash
+# Inspect your bundle to see if you've met your applications requirements
+bundle check
+```
- # Show source location of a specific gem in your bundle
- bundle show [gemname]
-
- # Generate a skeleton Gemfile to start your path to using Bundler
- bundle init
+```bash
+# List all gems in your bundle
+bundle list
+```
+
+```bash
+# Show source location of a specific gem in your bundle
+bundle show [gemname]
+```
+
+```bash
+# Generate a skeleton Gemfile to start your path to using Bundler
+bundle init
+```
**Updating**
@@ -84,11 +98,15 @@ new versions. Alternatively you can specify an individual gem to update, and
bundler will only update that gem to the latest version available in the
specified repository.
- # Update all gems specified to the latest versions available
- bundle update
+```bash
+# Update all gems specified to the latest versions available
+bundle update
+```
- # Update just i18n to the latest gem version available
- bundle update i18n
+```bash
+# Update just i18n to the latest gem version available
+bundle update i18n
+```
**Requiring**
@@ -99,24 +117,28 @@ of your gems loadpaths, and `require` will load all of your specified gems.
Requiring `bundler/setup` is the same as calling `Bundler.setup` yourself, and
is the recommended method in the gembundler documentation.
- # If you're using Ruby 1.9 you'll need to specifially load rubygems
- require 'rubygems'
+```ruby
+# If you're using Ruby 1.9 you'll need to specifially load rubygems
+require 'rubygems'
- # and now load bundler with your dependencies load paths
- require 'bundler/setup'
+# and now load bundler with your dependencies load paths
+require 'bundler/setup'
- # next you'll have to do the gem requiring yourself
- require 'sinatra'
- require 'i18n'
+# next you'll have to do the gem requiring yourself
+require 'sinatra'
+require 'i18n'
+```
Now if say you skip the last step, and just auto require gems from your groups
- require 'rubygems'
- require 'bundler/setup'
-
- # this will require all the gems not specified to a given group (default)
- # and gems specified in your test group
- Bundler.require(:default, :test)
+```ruby
+require 'rubygems'
+require 'bundler/setup'
+
+# this will require all the gems not specified to a given group (default)
+# and gems specified in your test group
+Bundler.require(:default, :test)
+```
### Resources
View
72 development/i18n.md
@@ -4,8 +4,10 @@ How can I internationalize my application? {#i18n}
We will rely on the `i18n` gem to handle internationalisation
of strings and objects, and to manage fallbacks on available locales
- require 'i18n'
- require 'i18n/backend/fallbacks'
+```ruby
+require 'i18n'
+require 'i18n/backend/fallbacks'
+```
The following configuration is necessary on I18n so that:
@@ -14,35 +16,43 @@ The following configuration is necessary on I18n so that:
* all the transalations are read from YAML files located in the
`locales` directory
- configure
- I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
- I18n.load_path, Dir[File.join(settings.root, 'locales', '*.yml')]
- I18n.backend.load_translations
- end
+```ruby
+configure
+ I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
+ I18n.load_path, Dir[File.join(settings.root, 'locales', '*.yml')]
+ I18n.backend.load_translations
+end
+```
Now we need to choose the locale that the user wants. There are several
solutions (and some can even be mixed together): browser preference,
spefic URL, dedicated subdomain, cookies/session management.
Only the first three will be shown below:
-* Browser preference (requires `rack-contrib`)
+### Browser preference (requires `rack-contrib`)
- use Rack::Locale
+```ruby
+use Rack::Locale
+```
-* Specific URL
+### Specific URL
- before '/:locale/*' do
- I18n.locale = params[:locale]
- request.path_info = '/' + params[:splat ][0]
- end
+```ruby
+before '/:locale/*' do
+ I18n.locale = params[:locale]
+ request.path_info = '/' + params[:splat ][0]
+end
+```
-* Dedicated subdomain
+### Dedicated subdomain
- before do
- if (locale = request.host.split('.')[0]) != 'www'
- I18n.locale = locale
- end
- end
+```ruby
+before do
+ if (locale = request.host.split('.')[0]) != 'www'
+ I18n.locale = locale
+ end
+end
+```
We have all the necessary information to deliver to the user
texts/pages in their native language. And for that we will need to
@@ -51,8 +61,10 @@ select strings and templates according to the desired locale.
Selection of localized strings/objects is easy as it only requires
use of standard methods from `I18n`
- I18n.t(:token)
- I18n.l(Time.now)
+```ruby
+I18n.t(:token)
+I18n.l(Time.now)
+```
For rendering the templates matching the desired locale, we need to
extend the `find_template` method. It needs to select the first
@@ -60,11 +72,13 @@ template matching the user locale (or at least one acceptable
fallback). To help in the selection process templates stored
in the `views` directory are suffixed by the name of the locale.
- helpers do
- def find_template(views, name, engine, &block)
- I18n.fallbacks[I18n.locale].each { |locale|
- super(views, "#{name}.#{locale}", engine, &block) }
- super(views, name, engine, &block)
- end
- end
+```ruby
+helpers do
+ def find_template(views, name, engine, &block)
+ I18n.fallbacks[I18n.locale].each { |locale|
+ super(views, "#{name}.#{locale}", engine, &block) }
+ super(views, name, engine, &block)
+ end
+end
+```
View
12 development/shotgun.md
@@ -9,14 +9,18 @@ available on Windows and JRuby.
Usage is rather simple:
- gem install shotgun # run only once, to install shotgun
- shotgun my_app.rb
+```bash
+gem install shotgun # run only once, to install shotgun
+shotgun my_app.rb
+```
If you want to run a modular application, create a file named `config.ru` with
similar content:
- require File.expand_path '../my_app.rb', __FILE__
- run MyApp
+```ruby
+require File.expand_path '../my_app.rb', __FILE__
+run MyApp
+```
And run it by calling `shotgun` without arguments.
View
44 development/sinatra-reloader.md
@@ -10,36 +10,44 @@ projects.
Install it by running
- gem install sinatra-reloader
+```bash
+gem install sinatra-reloader
+```
If you use the top level DSL, you just have to require it in development mode:
- require "sinatra"
- require "sinatra/reloader" if development?
-
- get('/') { 'change me!' }
+```ruby
+require "sinatra"
+require "sinatra/reloader" if development?
+
+get('/') { 'change me!' }
+```
When using a modular style application, you have to register the
`Sinatra::Reloader` extension:
- require "sinatra/base"
- require "sinatra/reloader"
-
- class MyApp < Sinatra::Base
- configure :development do
- register Sinatra::Reloader
- end
- end
+```ruby
+require "sinatra/base"
+require "sinatra/reloader"
+
+class MyApp < Sinatra::Base
+ configure :development do
+ register Sinatra::Reloader
+ end
+end
+```
For safety and performance reason, Sinatra::Reloader will per default only
reload files defining routes. You can, however, add files to the list of
reloadable files by using `also_reload`:
- require "sinatra"
+```ruby
+require "sinatra"
- configure :development do |config|
- require "sinatra/reloader"
- config.also_reload "models/*.rb"
- end
+configure :development do |config|
+ require "sinatra/reloader"
+ config.also_reload "models/*.rb"
+end
+```
View
184 embed/event-machine.md
@@ -9,109 +9,113 @@ Below is a (working) code-sample for running a simple HelloWorld Sinatra app
within EventMachine. I've also provided a simple example of deferring tasks
within your Sinatra call.
- require 'eventmachine'
- require 'sinatra/base'
- require 'thin'
-
-
- # This example shows you how to embed Sinatra into your EventMachine
- # application. This is very useful if you're application needs some
- # sort of API interface and you don't want to use EM's provided
- # web-server.
-
- def run(opts)
-
- # Start he reactor
- EM.run do
-
- # define some defaults for our app
- server = opts[:server] || 'thin'
- host = opts[:host] || '0.0.0.0'
- port = opts[:port] || '8181'
- web_app = opts[:app]
-
- # create a base-mapping that our application will set at. If I
- # have the following routes:
- #
- # get '/hello' do
- # 'hello!'
- # end
- #
- # get '/goodbye' do
- # 'see ya later!'
- # end
- #
- # Then I will get the following:
- #
- # mapping: '/'
- # routes:
- # /hello
- # /goodbye
- #
- # mapping: '/api'
- # routes:
- # /api/hello
- # /api/goodbye
- dispatch = Rack::Builder.app do
- map '/' do
- run web_app
- end
- end
-
- # NOTE that we have to use an EM-compatible web-server. There
- # might be more, but these are some that are currently available.
- unless ['thin', 'hatetepe', 'goliath'].include? server
- raise "Need an EM webserver, but #{server} isn't"
- end
-
- # Start the web server. Note that you are free to run other tasks
- # within your EM instance.
- Rack::Server.start({
- app: dispatch,
- server: server,
- Host: host,
- Port: port
- })
+```ruby
+require 'eventmachine'
+require 'sinatra/base'
+require 'thin'
+
+
+# This example shows you how to embed Sinatra into your EventMachine
+# application. This is very useful if you're application needs some
+# sort of API interface and you don't want to use EM's provided
+# web-server.
+
+def run(opts)
+
+ # Start he reactor
+ EM.run do
+
+ # define some defaults for our app
+ server = opts[:server] || 'thin'
+ host = opts[:host] || '0.0.0.0'
+ port = opts[:port] || '8181'
+ web_app = opts[:app]
+
+ # create a base-mapping that our application will set at. If I
+ # have the following routes:
+ #
+ # get '/hello' do
+ # 'hello!'
+ # end
+ #
+ # get '/goodbye' do
+ # 'see ya later!'
+ # end
+ #
+ # Then I will get the following:
+ #
+ # mapping: '/'
+ # routes:
+ # /hello
+ # /goodbye
+ #
+ # mapping: '/api'
+ # routes:
+ # /api/hello
+ # /api/goodbye
+ dispatch = Rack::Builder.app do
+ map '/' do
+ run web_app
end
end
-
- # Our simple hello-world app
- class HelloApp < Sinatra::Base
- # threaded - False: Will take requests on the reactor thread
- # True: Will queue request for background thread
- configure do
- set :threaded, false
- end
-
- # Request runs on the reactor thread (with threaded set to false)
- get '/hello' do
- 'Hello World'
- end
-
- # Request runs on the reactor thread (with threaded set to false)
- # and returns immediately. The deferred task does not delay the
- # response from the web-service.
- get '/delayed-hello' do
- EM.defer do
- sleep 5
- end
- 'I\'m doing work in the background, but I am still free to take requests'
- end
+ # NOTE that we have to use an EM-compatible web-server. There
+ # might be more, but these are some that are currently available.
+ unless ['thin', 'hatetepe', 'goliath'].include? server
+ raise "Need an EM webserver, but #{server} isn't"
end
- # start the application
- run app: HelloApp.new
+ # Start the web server. Note that you are free to run other tasks
+ # within your EM instance.
+ Rack::Server.start({
+ app: dispatch,
+ server: server,
+ Host: host,
+ Port: port
+ })
+ end
+end
+
+# Our simple hello-world app
+class HelloApp < Sinatra::Base
+ # threaded - False: Will take requests on the reactor thread
+ # True: Will queue request for background thread
+ configure do
+ set :threaded, false
+ end
+
+ # Request runs on the reactor thread (with threaded set to false)
+ get '/hello' do
+ 'Hello World'
+ end
+
+ # Request runs on the reactor thread (with threaded set to false)
+ # and returns immediately. The deferred task does not delay the
+ # response from the web-service.
+ get '/delayed-hello' do
+ EM.defer do
+ sleep 5
+ end
+ 'I\'m doing work in the background, but I am still free to take requests'
+ end
+end
+# start the application
+run app: HelloApp.new
+```
You can run this simply with the command:
- ruby em-sinatra-test.rb # em-sinatra-test.rb is the filename of the above-code
+```bash
+ruby em-sinatra-test.rb # em-sinatra-test.rb is the filename of the above-code
+```
You should also be able to test that it is working correctly with the
following `ab` command:
- ab -c 10 -n 100 http://localhost:8181/delayed-hello
+```bash
+ab -c 10 -n 100 http://localhost:8181/delayed-hello
+```
If this finishes in "zero point something" seconds, then you have successfully
setup Sinatra to run within EM and you are taking requests on the event-loop
View
61 helpers/partials.md
@@ -2,39 +2,44 @@ Implementation of Rails style partials
--------------------------------------
Using partials in your views is a great way to keep them clean. Since Sinatra takes the hands off approach to framework
-design, you'll have to implement a partial handler yourself.
+design, you'll have to implement a partial handler yourself.
Here is a really basic version:
- # Usage: partial :foo
- helpers do
- def partial(page, options={})
- haml page, options.merge!(:layout => false)
- end
- end
+```ruby
+# Usage: partial :foo
+helpers do
+ def partial(page, options={})
+ haml page, options.merge!(:layout => false)
+ end
+end
+```
A more advanced version that would handle passing local options, and looping over a hash would look like:
- # Render the page once:
- # Usage: partial :foo
- #
- # foo will be rendered once for each element in the array, passing in a local variable named "foo"
- # Usage: partial :foo, :collection => @my_foos
+```ruby
+# Render the page once:
+# Usage: partial :foo
+#
+# foo will be rendered once for each element in the array, passing in a local
+# variable named "foo"
+# Usage: partial :foo, :collection => @my_foos
- helpers do
- def partial(template, *args)
- options = args.extract_options!
- options.merge!(:layout => false)
- if collection = options.delete(:collection) then
- collection.inject([]) do |buffer, member|
- buffer << haml(template, options.merge(
- :layout => false,
- :locals => {template.to_sym => member}
- )
- )
- end.join("\n")
- else
- haml(template, options)
- end
- end
+helpers do
+ def partial(template, *args)
+ options = args.extract_options!
+ options.merge!(:layout => false)
+ if collection = options.delete(:collection) then
+ collection.inject([]) do |buffer, member|
+ buffer << haml(template, options.merge(
+ :layout => false,
+ :locals => {template.to_sym => member}
+ )
+ )
+ end.join("\n")
+ else
+ haml(template, options)
end
+ end
+end
+```
View
38 helpers/partials_using_the_sinatra-partial_gem.md
@@ -5,33 +5,41 @@ sinatra-partial gem.
Add the gem to your `Gemfile`:
- gem 'sinatra-partial', require: 'sinatra/partial'
+```ruby
+gem 'sinatra-partial', require: 'sinatra/partial'
+```
Register the extension (you don't have to do this for classic style apps):
- class SomeApp < Sinatra::Base
- configure do
- register Sinatra::Partial
- end
+```ruby
+class SomeApp < Sinatra::Base
+ configure do
+ register Sinatra::Partial
+ end
- # ...
- end
+ # ...
+end
+```
And enjoy!
- partial 'some_partial', template_engine: :erb
+```ruby
+partial 'some_partial', template_engine: :erb
+```
To avoid telling `partial` which template engine to use, you can configure it
globally:
- class SomeApp < Sinatra::Base
- configure do
- register Sinatra::Partial
- set :partial_template_engine, :erb
- end
+```ruby
+class SomeApp < Sinatra::Base
+ configure do
+ register Sinatra::Partial
+ set :partial_template_engine, :erb
+ end
- # ...
- end
+ # ...
+end
+```
### More information
View
333 middleware/rack_auth_basic_and_digest.md
@@ -5,47 +5,53 @@ You can easily protect your Sinatra application using HTTP
[Basic][httpbasic] and [Digest][httpdigest] Authentication with the
help of Rack middlewares.
-## Protect the whole application
+## Protect the whole application
These examples show how to protect the whole application (all routes).
-### HTTP Basic Authentication
+### HTTP Basic Authentication
For classic applications:
- #main.rb
- require 'sinatra'
-
- use Rack::Auth::Basic, "Protected Area" do |username, password|
- username == 'foo' && password == 'bar'
- end
-
- get '/' do
- "secret"
- end
-
- get '/another' do
- "another secret"
- end
-
+```ruby
+#main.rb
+
+require 'sinatra'
+
+use Rack::Auth::Basic, "Protected Area" do |username, password|
+ username == 'foo' && password == 'bar'
+end
+
+get '/' do
+ "secret"
+end
+
+get '/another' do
+ "another secret"
+end
+```
+
For modular applications:
- #main.rb
-
- require 'sinatra/base'
-
- class Protected < Sinatra::Base
-
- use Rack::Auth::Basic, "Protected Area" do |username, password|
- username == 'foo' && password == 'bar'
- end
-
- get '/' do
- "secret"
- end
-
- end
-
- Protected.run!
+
+```ruby
+#main.rb
+
+require 'sinatra/base'
+
+class Protected < Sinatra::Base
+
+ use Rack::Auth::Basic, "Protected Area" do |username, password|
+ username == 'foo' && password == 'bar'
+ end
+
+ get '/' do
+ "secret"
+ end
+
+end
+
+Protected.run!
+```
To try these examples just run `ruby main.rb -p 4567` and visit
[http://localhost:4567][localhost]
@@ -57,58 +63,66 @@ To use digest authentication with current versions of Rack a
For classic applications:
- #main.rb
-
- require 'sinatra'
-
- get '/' do
- "secret"
- end
-
+```ruby
+#main.rb
+
+require 'sinatra'
+
+get '/' do
+ "secret"
+end
+```
+
- - -
- #config.ru
-
- require File.expand_path '../main.rb', __FILE__
-
- app = Rack::Auth::Digest::MD5.new(Sinatra::Application) do |username|
+```ruby
+#config.ru
+
+require File.expand_path '../main.rb', __FILE__
+
+app = Rack::Auth::Digest::MD5.new(Sinatra::Application) do |username|
+ {'foo' => 'bar'}[username]
+end
+
+app.realm = 'Protected Area'
+app.opaque = 'secretkey'
+
+run app
+```
+
+For modular applications:
+
+```ruby
+#main.rb
+
+require 'sinatra/base'
+
+class Protected < Sinatra::Base
+
+ get '/' do
+ "secret"
+ end
+
+ def self.new(*)
+ app = Rack::Auth::Digest::MD5.new(super) do |username|
{'foo' => 'bar'}[username]
end
-
app.realm = 'Protected Area'
app.opaque = 'secretkey'
-
- run app
-
-For modular applications:
+ app
+ end
+end
+```
- #main.rb
-
- require 'sinatra/base'
-
- class Protected < Sinatra::Base
-
- get '/' do
- "secret"
- end
-
- def self.new(*)
- app = Rack::Auth::Digest::MD5.new(super) do |username|
- {'foo' => 'bar'}[username]
- end
- app.realm = 'Protected Area'
- app.opaque = 'secretkey'
- app
- end
- end
-
- - -
-
- #config.ru
-
- require File.expand_path '../main.rb', __FILE__
-
- run Protected
+
+```ruby
+#config.ru
+
+require File.expand_path '../main.rb', __FILE__
+
+run Protected
+```
To try these examples just run `rackup -p 4567` and visit
@@ -125,45 +139,49 @@ and a `config.ru` file.
First the `main.rb`
- #main.rb
-
- require 'sinatra/base'
-
- class Protected < Sinatra::Base
-
- use Rack::Auth::Basic, "Protected Area" do |username, password|
- username == 'foo' && password == 'bar'
- end
-
- get '/' do
- "secret"
- end
-
- get '/another' do
- "another secret"
- end
-
- end
-
- class Public < Sinatra::Base
-
- get '/' do
- "public"
- end
-
- end
+```ruby
+#main.rb
+
+require 'sinatra/base'
+
+class Protected < Sinatra::Base
+
+ use Rack::Auth::Basic, "Protected Area" do |username, password|
+ username == 'foo' && password == 'bar'
+ end
+
+ get '/' do
+ "secret"
+ end
+
+ get '/another' do
+ "another secret"
+ end
+
+end
+
+class Public < Sinatra::Base
+
+ get '/' do
+ "public"
+ end
+
+end
+```
And the `config.ru`
- #config.ru
-
- require File.expand_path '../main.rb', __FILE__
-
- run Rack::URLMap.new({
- "/" => Public,
- "/protected" => Protected
- })
-
+```ruby
+#config.ru
+
+require File.expand_path '../main.rb', __FILE__
+
+run Rack::URLMap.new({
+ "/" => Public,
+ "/protected" => Protected
+})
+```
+
To try these examples just run `rackup -p 4567` and visit
[http://localhost:4567][localhost]
@@ -173,50 +191,53 @@ The resulting routes are explained at the bottom of this page.
First the `main.rb`
- #main.rb
-
- require 'sinatra/base'
-
- class Protected < Sinatra::Base
-
- get '/' do
- "secret"
- end
-
- get '/another' do
- "another secret"
- end
-
- def self.new(*)
- app = Rack::Auth::Digest::MD5.new(super) do |username|
- {'foo' => 'bar'}[username]
- end
- app.realm = 'Protected Area'
- app.opaque = 'secretkey'
- app
- end
- end
-
- class Public < Sinatra::Base
-
- get '/' do
- "public"
- end
-
+```ruby
+#main.rb
+
+require 'sinatra/base'
+
+class Protected < Sinatra::Base
+
+ get '/' do
+ "secret"
+ end
+
+ get '/another' do
+ "another secret"
+ end
+
+ def self.new(*)
+ app = Rack::Auth::Digest::MD5.new(super) do |username|
+ {'foo' => 'bar'}[username]
end
-
+ app.realm = 'Protected Area'
+ app.opaque = 'secretkey'
+ app
+ end
+end
+
+class Public < Sinatra::Base
+
+ get '/' do
+ "public"
+ end
+
+end
+```
+
And the `config.ru`
- #config.ru
-
- require File.expand_path '../main.rb', __FILE__
-
- run Rack::URLMap.new({
- "/" => Public,
- "/protected" => Protected
- })
-
-
+```ruby
+#config.ru
+
+require File.expand_path '../main.rb', __FILE__
+
+run Rack::URLMap.new({
+ "/" => Public,
+ "/protected" => Protected
+})
+```
+
To try these examples just run `rackup -p 4567` and visit
[http://localhost:4567][localhost]
@@ -224,7 +245,7 @@ To try these examples just run `rackup -p 4567` and visit
### The resulting routes
The routes display the following:
-
+
* `/` displays "public"
* `/protected` displays "secret"
* `/protected/another` displays "another secret"
View
108 middleware/rack_parser.md
@@ -8,11 +8,13 @@ Often this is a two step process -- first parsing the message string into
predictable data structures, then loading that into models. So a typical route
might look like
- post '/messages'
- message = Message.from_hash( ::MultiJson.decode(request.body) )
- message.save
- halt 202, {'Location' => "/messages/#{message.id}"}, ''
- end
+```ruby
+post '/messages'
+ message = Message.from_hash( ::MultiJson.decode(request.body) )
+ message.save
+ halt 202, {'Location' => "/messages/#{message.id}"}, ''
+end
+```
And your Message model would have an appropriate `#from_hash` method that
grabs what it needs from the parsed message and throws it into a new instance.
@@ -20,18 +22,20 @@ grabs what it needs from the parsed message and throws it into a new instance.
If your application has several different endpoints, all using the same
content-type, you could save some repitition by moving it to a helper:
- helpers do
- def parsed_body
- ::MultiJson.decode(request.body)
- end
- end
-
- post '/orders'
- order = Order.from_hash( parsed_body )
- order.process
- # ....
- end
-
+```ruby
+helpers do
+ def parsed_body
+ ::MultiJson.decode(request.body)
+ end
+end