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

Sinatra URL Matching


Now that we've got a number of handlers in our application, we can see what can happen if you accidentally block one of your handlers. The third handler, /hello/bob will never be able to run. Why? Because the URL /hello/bob also matches the first handler. The handlers are matched top to bottom (in the order they're defined in the file) and the first handler that matches the URL will be run. If a special handler for /hello/bob is needed, it will need to come before /hello/:name or it won't work.

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

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

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

# This handler is OK though, since the first
# handler must have a second part after the
# slash
get '/hello' do
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Hiding Handlers

©2014 About.com. All rights reserved.