Mount Sinatra app inside a rails app and sharing layout

Mike picture Mike · Jul 28, 2011 · Viewed 9.2k times · Source

I would like to mount a sinatra application in my rails app. But I would like this one to share the same layout.

The iframe could work but do you have any other idea ?

Thanks

Answer

Holger Just picture Holger Just · Aug 7, 2011

You basically need to do two things:

You need to tell the Rails router that a certain URL path is to be handled by another Rack app (in your case a Sinata app). This can be done by adding this to your routes.rb:

match "/sinatra" => MySinatraApp, :anchor => false

Having done that, you can create your app like so:

class MySinatraApp < Sinatra::Base
  get "/" do
    "Hello Sinatra World"
  end
end

The second step now is to tell your Sinatra app to use the rails layout which by default lives in app/views/layouts/application.html.erb for Rails 3.1. by default, Sinatra uses ./views/layout.ext (with ext being the extension of your chosen template system). So you basically, have to tell Sinatra to

  1. use another directory to find views and layouts instead of the default ./views
  2. use another template file as the default layout.

Both can be achieved by setting the following in your sinatra app:

set :views, "/path/to/your/railsapp/views"
set :erb, layout => :"layout/application" # or whatever rendering engine you chose