How mix in routes in Sinatra for a better structure

roundrobin picture roundrobin · Jan 13, 2011 · Viewed 8.3k times · Source

I found nothing about how I can mix-in routes from another module, like this:

module otherRoutes
  get "/route1" do

  end
end    

class Server < Sinatra::Base
  include otherRoutes

  get "/" do
    #do something
  end
end

Is that possible?

Answer

aledalgrande picture aledalgrande · Jul 27, 2011

You don't do include with Sinatra. You use extensions together with register.

I.e. build your module in a separate file:

require 'sinatra/base'

module Sinatra
  module OtherRoutes
    def self.registered(app)
      app.get "/route1" do
        ...
      end
    end
  end
  register OtherRoutes # for non modular apps, just include this file and it will register
end

And then register:

class Server < Sinatra::Base
  register Sinatra::OtherRoutes
  ...
end

It's not really clear from the docs that this is the way to go for non-basic Sinatra apps. Hope it helps others.