1. Computing
Send to a Friend via Email

Sinatra URL Matching

By

Named parameters are portions of the URL that will act as a parameter. For example, /hello/:name will match any URL that looks like /hello/alice or /hello/bob. In the request handler, the contents of the :name portion of the request URL will be available as params[:name].

Named parameters match any character up to the next slash. While they're usually used for just single word parameters, or perhaps parameters with a number of words separated by dashes, they can be used for more complex parameters. Though regular expressions may be more appropriate than named parameters in that case.

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

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

get '/tell/:name/:greeting' do
  "#{params[:greeting]} #{params[:name]}"
end
  
# This handler will never match, as the first
# handler hides it
get '/hello/bob' do
  "Hi there Bob!!"
end

# This handler is OK though, since the first
# handler must have a second part after the
# slash
get '/hello' do
  "Hello!"
end

Here, the /hello/:name handler is something we've seen before. The handler is quite straight forward, it will take any string passed in the :name parameter section and add it to the response.

The second /tell/:name/:greeting handler is a little more complex. Here, the :name parameter will match any string of characters without a slash in it. This includes spaces and other symbols. So you can make a request to /tell/Alice and Bob/Hi there and everything will go as expected.

©2014 About.com. All rights reserved.