BootStrapping a Sinatra app
In an effort to simplify my Sinatra app startup and configuration process I’ve built out a very simple bootstrapping library. It’s robust enough to cover the needs for a small to mid size app, but simple enough that it’s not overkill for use with Sinatra.
boostraps.rb
In my config directory I have two files: bootstraps.rb and environment.rb.
The former contains three classes DataStore, Configuration, and Initializer. When you invoke the class method boot! on Initializer it pulls in the environment.rb, loads up the configured gems and then loads up all the files in whatever library directories have been specified.
Use within your Sinatra::Base subclass takes the form:
require 'config/bootstraps' module MyModule class App < Sinatra::Base configure do Config = BootStraps::Initializer.config Config.db.connect bar = Config.global[:foo] end end end
Environment.rb
The above is nice and quiet as it should be. Behind the scenes we’ve told ol’ BootStraps a bunch of stuff about what our app looks like:
BootStraps::Initializer.configure do |config| #Configure the db library and settings config.db.lib = 'ActiveRecord::Base' config.db.init_method = :establish_connection config.db.init_args = { :adapter => 'sqlite3', :dbfile => "#{config.root}db/#{config.env}.sqlite3"} #default our environment to production config.default_env = 'production' #require a ActiveRecord on boot config.gems['activerecord'] = '>=2.2' #arbitrary setting config.global[:foo] = 'bar' end
Other stuff
The best part that you don’t see here is the ability to add libraries to app/[models,ext]/ or lib/ and have them required for you. Again, the point is to limit the knowledge/effort needed to contribute new code to the app.
kinks
It’s quirky in some places (you have to specify something for a gem version even if its nil) but its a relatively clean app boostrapping solution. You can check out my current use case in more detail here so long as you ignore the rest of the app :D.
Comments(0)