Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How mix in routes in Sinatra for a better structure

Tags:

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?

like image 263
roundrobin Avatar asked Jan 13 '11 14:01

roundrobin


People also ask

What is a route in Sinatra?

In Sinatra, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block. The matching route defined in the controller would look like this: get '/medicines' do # some code to get all the medicines # some code to render the correct HTML page end.

What is Sinatra :: Base?

Sinatra::Base is the Sinatra without delegation. Consider the following code with delegation: # app.rb require 'sinatra' get '/' do render :template end.


2 Answers

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.

like image 111
aledalgrande Avatar answered Oct 08 '22 02:10

aledalgrande


You could do this:

module OtherRoutes   def self.included( app )     app.get "/route1" do       ...     end   end end  class Server < Sinatra::Base   include OtherRoutes   ... end 

Unlike Ramaze, Sinatra's routes are not methods, and so cannot use Ruby's method lookup chaining directly. Note that with this you can't later monkey-patch OtherRoutes and have the changes reflected in Server; this is just a one-time convenience for defining the routes.

like image 31
Phrogz Avatar answered Oct 08 '22 02:10

Phrogz