Skip navigation

Active Product Development

4 Posts tagged with the sinatra tag

ActiveRecord is great but it can be a little scary to think about using it without Rails. Here's a quick example of using it with Sinatra.


The first thing we'll want to do is get the ActiveRecord gem by itself (throughout this tutorial I'm assuming you're using Bundler to manage your gems):


gem 'activerecord', :require => 'active_record'


Next up, in the configure block of our Sinatra app, we'll set up the AR connection to our database:


ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => 'db/development.db')


Of course, if you want to stay flexible, you can move your database config into a YAML file (laid out the same as the Rails standard config/database.yml file) and pull the connection details from that:


db_config = YAML::load(,'config','database.yml')))[Sinatra::Application.environment]

Now that AR is ready to go we can include our models. I like to move my models into separate files, similar to Rails's app/models, so I tell Sinatra to include every file in that directory:


Dir.glob('./app/models/*').each { |r| require r }


Believe it or not, that's really all you need to do to start using AR in your Sinatra application! The only missing link is database migrations. AR comes with a huge Rake file full of tasks like db:migrate, but unfortunately those rely on being inside the shell of Rails (they look for environment variables like RAILS_ENV and the base Rails object all over the place). Here's a very simple piece of code that will enable the standard db:migrate task:


require 'bundler'

desc "Migrate the database through scripts in db/migrate."
task :migrate do
  ActiveRecord::Base.establish_connection(YAML.load('config','database.yml')))[ENV['ENV'] ? ENV['ENV'] : 'development'])


This assumes that your migration files are in db/migrate. When you want to migrate in an environment other than development just set the ENV variable:


rake db:migrate ENV=production


That's it! There are a couple of different database ORM libraries out there besides ActiveRecord (like Sequel and Datamapper) but AR is the most popular today and it's easy to use it in all of your web apps, whether they're Rails or not.

10,436 Views 0 Comments Permalink Tags: ruby, sinatra, rails, database, activerecord

Ruby on Rails comes with a bunch of great rake tasks to help you work with your application. One of them is rake stats which counts the lines of code in your controllers, models and tests. It's a pretty neat utility that we use all the time to make the Java developers jealous.


I've been working on a little Sinatra application and wanted to use the same functionality. The rake stats command used the CodeStatistics class from one of the core Rails packages called railties (that's "rail-ties" as in the wooden slats that hold up train tracks, not "rail-tees" like t-shirts about trains). Now, the good Ruby developer in me says to simply require 'railties/code_statistics' from in my Sinatra application. However, I also realize that my Sinatra application has nothing to do with Rails and never will. So I did the unthinkable: copy-paste. In this case I don't think it's that bad: code_statistics probably hasn't changed much since Rails 1.0 and it's not something that I care about keeping in sync with the master development branch of Rails. Don't sweat it.


I put code_statistics.rb in a new directory in my Sinatra app called vendor which is a Rails convention for code from third-parties. Normally I would just put this code into lib, but in this case rake stats includes the lines of code in any files in lib, and I didn't want to throw off my numbers. In my Rakefile I added a new task (also copied from the Rails default Rakefile with a couple modifications):

desc "Report code statistics" task :stats do   require './vendor/code_statistics'     STATS_DIRECTORIES = [     %w(Controllers        app/controllers),     %w(Helpers            app/helpers),     %w(Models             app/models),     %w(Libraries          lib/),     %w(Migrations         db/migrations),     %w(Views              app/views)   ].collect { |name, dir| [ name, "./#{dir}" ] }.select { |name, dir| }*STATS_DIRECTORIES).to_s end


The modifications in this case are the directories that should be scanned for code lines. By default Rails doesn't include your views as counting towards your totals, but I wanted them to. I also have lots of migrations and would like to know how those contribute as well.  If you have any directories in addition to these just add them to the STATS_DIRECTORIES constant. I also wanted to count the number of comments in my code. I'm a big proponent of commenting and I'd like to know what ratio of my code is used to tell my future self how everything works. You can get a copy of my code_statistics.rb file (with comment-counting mods) here:


And that's it! Now just rake stats from the root of your Sinatra app and you'll see something like this:


+----------------------+-------+-------+----------+---------+---------+-----+-------+ | Name                 | Lines |   LOC | Comments | Classes | Methods | M/C | LOC/M | +----------------------+-------+-------+----------+---------+---------+-----+-------+ | Controllers          |    65 |    50 |        8 |       0 |       0 |   0 |     0 | | Helpers              |    41 |    32 |        0 |       0 |       7 |   0 |     2 | | Models               |    12 |    10 |        0 |       2 |       1 |   0 |     8 | | Libraries            |     8 |     6 |        1 |       2 |       1 |   0 |     4 | | Migrations           |    78 |    71 |        4 |       0 |       0 |   0 |     0 | | Views                |    45 |    39 |        0 |       0 |       0 |   0 |     0 | +----------------------+-------+-------+----------+---------+---------+-----+-------+ | Total                |   249 |   208 |       13 |       4 |       9 |   2 |    21 | +----------------------+-------+-------+----------+---------+---------+-----+-------+   Code LOC: 208     Test LOC: 0     Code to Test Ratio: 1:0.0


853 Views 0 Comments Permalink Tags: ruby, sinatra, rails, rake

I put together a presentation this past week about building small, fast websites with Ruby and Sinatra, and then deploying them on Heroku. I had less-technical users in mind with this presentation. If you're a hardcore developer you have no problem setting up a web server from scratch. This is geared more towards designers who can make beautiful sites but aren't used to making them dynamic or pushing them public to the world.


You can download the sample code used in the presentation from here:


1,962 Views 0 Comments Permalink Tags: development, leg, web, ruby, sinatra, heroku

Active Widgets

Posted by RobCameron.2.16b Mar 1, 2010

Hi, I'm Rob and I'm a Software Architect on the Light Engineering Group here at Active. LEG, as we call it, was modeled after the LED group at LinkedIn. LinkedIn was looking for a way to rapidly prototype new technologies and architectures with Ruby on Rails. Their first product was Bumper Sticker which at one point was the mostly highly trafficed Facebook application in existence! You can find many of the fruits of LEG's labor at


This morning we officially launched our new Active Widgets site at This was a quick two week project to create an embeddable window into's thousands of registerable events. The idea being that the blog you write about running/cycling/baseball can show a list of upcoming marathons/track events/Little League games in your area. The widget is customizable as far as what activities it displays, where it displays them, whether or not the user can change those settings, as well as the size and color of the widget itself. Once your done just click a button and you're given a couple of simple Javascript tags to drop onto your site wherever you want the widget to appear. And since the widget is written out onto your page like any other HTML, you can further customize it using your own CSS.




The Technical Stuff

This customization site (known as The Configurator) is a Sinatra application written in Ruby. There is no database—the data store is a single YAML file which defines a widget and what about it is customizable. The widget itself is written in Javascript and after minification with the YUI Compressor, the whole thing is 14K (for comparison, the Google homepage is 47K).


Since we planned on having the widget be embeddable on any website we couldn't use Ajax to pull in the event listings. Ajax is subject to strict cross-domain security policies set by your browser—you can only access servers in the same domain that the page itself was served from. This is quite a problem since search results are coming from  The workaround for this issue is to make server calls with <script> tags and then wrap the resulting code in a function call known as a callback. When the <script> tag is added to the page the browser immediately executes it as valid Javascript. Since this Javascript contains a function call (the callback) it looks a function you've already defined with the same name and calls it, passing in the returned data.


The server itself is an Amazon EC2 instance running in their cloud infrastructure. This allows us to quickly react to any scaling needs by simply spinning up a new instance of the same server and deploying the code to it. Nearly half our division's products are now running on EC2 and we're moving more there every day. We've found it be an fast, secure and cost effective way to get our applications live.


Stay tuned for more exciting projects from the LEG team!

2,216 Views 0 Comments Permalink Tags: events, widgets, leg, cloud_computing, amazon, ec2, labs, ruby, sinatra