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

Sinatra URL Matching


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."

get '/hello' do

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].

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. User Agents

©2014 About.com. All rights reserved.