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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With