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.


#./base_controller.rb
require 'sinatra/base'

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

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

#/controllers/module1_controller.rb
require File.join(File.dirname(__FILE__),'..', 'base_controller.rb')

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

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

# config.ru
require './base_controller.rb'
require './controllers/module1_controller.rb'

map '/' do
  run BaseController
end

map '/module1' do
  run Module1Controller
end

Note: the code snippets above assume that the base_controller.rb and config.ru 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:

WordPress.com Logo

You are commenting using your WordPress.com 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.