It’s easy to have useful libraries pass you by (RubyGems.orghttps://rubygems.org lists 31,448 gems as of writing) and sinatra namespace (now part of sinatra-contribhttps://rubygems.org/gems/sinatra-contrib) was just such a one.
I’ve started using it, but I wanted to see what happens when you’ve got a namespace defined with a route inside that is also the same as a route outside:
# encoding: UTF-8 root = File.expand_path File.dirname(__FILE__) require File.join( root , "app.rb" ) app = Rack::Builder.app do run TryOut::App end run app
# encoding: UTF-8 require "sinatra/base" require "sinatra/namespace" module TryOut class App < Sinatra::Base register Sinatra::Namespace get "/" do # matches / "Outside namespace - /" end # This route shows that you can have routes defined # outside the namespace that will be served ok get "/inside" do # matches /inside "Outside namespace - /inside" end # This route shows that you can have routes defined # outside the namespace that will be served ok get "/inside/elsewhere" do # matches /inside/elsewhere "Outside namespace - /inside/elsewhere" end # With this route defined here, this is used # and the one inside the namespace is not used get "/inside/nowhere" do # matches /inside/nowhere "Outside namespace - /inside/nowhere" end namespace "/inside" do get "/" do # matches /inside/ "Inside namespace - /" end get "/somewhere" do # matches /inside/somewhere "Inside namespace - somewhere" end get "/nowhere" do # matches /inside/nowhere "Inside namespace - /nowhere" end end # namespace # With the route defined after the namespace, *this isn't used* # and the one *inside the namespace is* # get "/inside/nowhere" do # matches /inside/nowhere # "Outside namespace - /nowhere" # end end # App end # Test
In the terminal:
rackup -p 9293 config.ru
And the output from each url, with the /inside/nowhere route defined outside and first:
Outside namespace - /
Outside namespace - /inside
Outside namespace - /inside/elsewhere
Outside namespace - /inside/nowhere
Inside namespace - /
Inside namespace - somewhere
Restarting the app with the /inside/nowhere route defined outside and after the namespace:
Inside namespace - /nowhere
That last one is the same regardless of whether the outside route is defined or not, as long as it’s after the namespace.
So, the namespace is flexible, allowing routes both inside and out with similar paths. That’s good. The order of the routes is also important, and follows the same rule as standard definition of routeshttp://www.sinatrarb.com/intro.html#Routes - first route that matches is the one that is invoked.
Only 31,447 gems to go…