Sinatra Code Organization

by Andrew Stewart
published November 15, 2012

I try to avoid the approach many people take to writing Sinatra apps, which is to place everything in the app.rb file. This gets very cluttered very fast.

Instead, I split out persistance and objects into models and lib directories, respectively.

So for example, a project might look like this:

$ tree
.
├── Gemfile
├── Gemfile.lock
├── config.ru
├── lib
|   ├── user_list_filter.rb
│   └── api_key_generator.rb
├── models
│   └── user.rb
├── app.rb
└── spec
    ├── lib
    │   ├── user_list_filter_spec.rb
    │   └── api_key_generator_spec.rb
    └── spec_helper.rb

To require everything in lib and models, I’ve got this in config.ru:

config.ru
directories = %w(models lib)

directories.each do |directory|
  Dir["#{File.dirname(__FILE__)}/#{directory}/*.rb"].each do |file|
    require file
  end
end

Simple enough, and allows for better code organization and much faster tests.