opensoul.org

Sinatra serenades Rails 2

December 10, 2010 code 3 min read

It turns out it’s really easy to mount a Sinatra application into your Rails 2 app (yes, there are still a few Rails 2 apps out there). Here’s how.

First, declare Sinatra as a gem dependency in config/environment.rb:

config.gem 'sinatra', :lib => 'sinatra/base'

Next, create a directory to put Sinatra apps in and add them to the Rails load path:

config.autoload_paths << Rails.root.join("app/sinatra")

Then, define a Sinatra app in a file in app/sinatra:

class TheJsonApi < Sinatra::Base
  before { content_type(:json) }

  get '/v2/foo' do
    {:foo => 'bar'}.to_json
  end
end

And finally, insert your Sinatra app as middleware:

config.after_initialize do
  config.middleware.insert_before("ActionController::Failsafe", "TheJsonApi")
end

Sinatra, being the classy framework that it is, is smart enough to act as a Rack middleware OR an endpoint (what’s the difference?). If you use it as a middleware, it will serve any routes that it knows about and pass on any that it doesn’t.

Why would you use Rails and Sinatra?

I’m working on large Rails application that consists mostly of an XML API. We’re working on a new version of the API with some significant changes. Since the new API will only have 7-10 endpoints, and only return JSON, we are thinking it will just be cleaner to build it as a Sinatra app. It will be easier to document and easier to maintain. And we are embedding it in the Rails app so it can make use of our existing models.

This content is open source. Suggest Improvements.

@bkeepers

avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.