Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

routes

sinatra

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
like image 367
tester Avatar asked Dec 04 '12 00:12

tester


People also ask

What is Sinatra framework?

Sinatra is a free and open source software web application library and domain-specific language written in Ruby. It is an alternative to other Ruby web application frameworks such as Ruby on Rails, Merb, Nitro, and Camping. It is dependent on the Rack web server interface. It is named after musician Frank Sinatra.


1 Answers

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.

like image 115
Miikka Avatar answered Oct 19 '22 01:10

Miikka