1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Sinatra URL Matching

By

The static URL handlers are those with a simple string for matching criteria. The only URLs that match these routes are those that match character for character. So, if I have a route of /hello, only a request for /hello will match. Anything similar such as /hello/world will not match. Since only an exact match will do, if your application uses only static routes it doesn't matter in which order they appear.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'

get '/hello' do
  'hello'
end

get '/hello/world' do
  'hello world'
end

In this example, the two separate handlers will not interfere with each other. Only requests to /hello or /hello/world will match these handlers. Requests to similar URLs like /hello/bob will match neither, and will make Sinatra throw a 404 (not found) error.

Static URLs can be useful for a range of things. Static pages, obviously, can use static URLs. Any handler that uses the POST, PUT or DELETE can also make use of static URLs. You can also use traditional URL parameters with static URLs, though this is not terribly pretty and doesn't really leverage Sinatra. Traditional CGI parameters can be passed to any handler with any type of route.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'

get '/hello' do
  "Hello #{params[:name]}"
end

A request to /hello?name=Bob will generate the string "Hello Bob".

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Static URLs

©2014 About.com. All rights reserved.