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

Sinatra URL Matching

By

Parameters can be extracted from a URL using regular expression capture groups. In this example, the URL contains a date. Rather than matching the date with a simple named parameter and parsing the date using a regular expression or split, the regular expression in the handler takes care of all this. This has the added benefit of matching only strings of a certain format, so you may have a handler that fetches (for example) blog posts by name or by date using the same first part of the URL.

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

get %r{/post/(\d\d)-(\d\d)-(\d\d\d\d)} do|month,day,year|
  "Post requested from #{month}/#{day} in #{year}"
end

get '/post/:title' do|title|
  "Post requested with a title of #{title}"
end

In this example, a request made to /post/10-04-2007 will match the handler with the regular expression. However, a request made to /post/some-title won't match the regular expression handler since the format doesn't match.

In this example, the capture groups were assigned to the block parameters month, day and year. However, if you don't want to do that, you can access them through the params[:captures] array. Note that even if you only have one capture group, params[:captures] will always be an array, unlike the wildcard params[:splat] key.

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Regular Expressions

©2014 About.com. All rights reserved.