1. Computing
Send to a Friend via Email

Sinatra URL Matching

By

A user agent string is sent by your web browser as part of an HTTP request to tell the server which web browser is in use. Sinatra includes support for matching these in your URL handlers, so you can have different responses for different clients. A list of user agent string can be found here.

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

get '/hello', :agent => /MSIE 6/ do
  "Seriously? Internet Explorer 6? Upgrade and come back."
end

get '/hello' do
  "Hello!"
end

In this example, if the user has request the page with Microsoft Internet Explorer 6, it will display a different message than if a user has requested a page with any other browser. Since agent matches using a regular expression, more can be done with that as well. Any capture groups you have in the agent regular expression will show up in params[:agent].

©2014 About.com. All rights reserved.