Sinatra Modular Applications with Ruby 1.9

Disclaimer: what I write here is something that is working for me, but I am not an expert, so I cannot declare this to be the best solution.

I am working on a small application that I know it will grow, so the traditional Sinatra application could be a mess when I have more than 10 routes.

So the strategy I have chosen is to create a base class called BaseController inheriting from Sinatra::Application, this base clase will handle global application settings.

require 'sinatra/base'

class BaseController < Sinatra::Base
  get '/' do
    'Home (base controller)'

Then, I create one controller class for each application module, each of this controllers should inherit from my BaseController.

require File.join(File.dirname(__FILE__),'..', 'base_controller.rb')

class Module1Controller < BaseController
  get '/' do
    'Module 1'

Finally, in the file I define the base routes for each controller.

require './base_controller.rb'
require './controllers/module1_controller.rb'

map '/' do
  run BaseController

map '/module1' do
  run Module1Controller

Note: the code snippets above assume that the base_controller.rb and files are located in the root directory while every all controller files are located under «/controllers» directory.

You can download the source code from here.

Deja una respuesta

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Salir /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Salir /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Salir /  Cambiar )

Conectando a %s

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.