How to get a list of all routes used in a Sinatra app?

tester picture tester · Dec 4, 2012 · Viewed 8.8k times · Source

Say I have:

require 'sinatra'

get '/' { "hi" }
get '/a' { "a" }
get '/b' { "b" }

Is there any easy to way obtain a list of all defined routes in my Sinatra application?

I investigated Sinatra::Base.routes, but that doesn't appear to contain the routes I just defined.

I was hoping to have a nice way to make a self documenting API like routes.each { |r| p r } to get:

/
/a
/b

Answer

Miikka picture Miikka · Dec 9, 2012

You should investigate Sinatra::Application.routes, which contains your routes. This prints the regular expressions of your route patterns:

require 'sinatra'

get '/'  do "root" end
get '/a' do "a" end
get '/b' do "b" end

Sinatra::Application.routes["GET"].each do |route|
  puts route[0]
end

To make things simpler, take look at the sinatra-advanced-routes extension. It gives you a nice API for introspecting the routes:

require 'sinatra'
require 'sinatra/advanced_routes'

get '/'  do "root" end
get '/a' do "a" end
get '/b' do "b" end

Sinatra::Application.each_route do |route|
  puts route.verb + " " + route.path
end

See the README of sinatra-advanced-routes for more documentation and examples.