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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.