Simple Sinatra Console

In the most recent little project, I found that I wanted to play more with DataMapper and my models to figure out the best way to write up the app methods. This project is, at its core, Sinatra, DataMapper, & Paperclip with some simple home-baked auth.

Running irb meant requiring all the model files and helpers, and connecting to the db etc etc. What I wanted was the Rails-like script/console (or rails s for the Rails3 folks).

It looks like tux has figured this out. You can follow along as an educational exercise if you like, but in the end, you should just install tux.

# Gemfile
group :development do
  gem 'tux'

If you’re putting models, etc in other directories, you may need to add something like this to your file

Dir[File.join(File.dirname(__FILE__),"{lib,models}/**/*.rb")].each do |file|
  require file

Assuming a file structure something like this:

  • /approot
    • /lib/
    • /models/
    • /views/
    • app.rb

and a new-ish Sinatra (i’m using ConfigFile from sinatra/config), you can have your own console in your app’s enviroment with this:

Then you can do stuff like this:

% bundle exec script/console.rb
loading config file '/projects/1890sinatra/config/config.yml'
1.9.3-p194 :001 > ContentResource.all
 => [] 
1.9.3-p194 :002 > ContentResource.create(:page => 'this', :section => 'that', :body => 'whatever * yo\n\n*yoyo')
 => #<ContentResource @id=1 @page="this" @section="that" @body="whatever * yo\\n\\n*yoyo"> 
1.9.3-p194 :003 > ContentResource.all                                            
 => [#<ContentResource @id=1 @page="this" @section="that" @body="whatever * yo\\n\\n*yoyo">] 
1.9.3-p194 :004 > settings
 => Sinatra::Application 
1.9.3-p194 :005 > settings.database_url
 => "postgres://localhost/mydb" 
1.9.3-p194 :006 > 

I accessed my ContentResource model defined in the models directory and accessed my configuration variables from config.yml in a nice simple ruby console.

Versions of note (not required versions, but for reference):

  • sinatra 1.3.2
  • sinatra-contrib 1.3.1
  • data_mapper 1.2.0
  • ruby 1.9.3