1. Computing

Sinatra URL Matching

By

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]}"
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
  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Hiding Handlers

©2014 About.com. All rights reserved.