Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mount Sinatra app inside a rails app and sharing layout

Tags:

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

like image 598
Mike Avatar asked Jul 28 '11 09:07

Mike


2 Answers

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 
like image 113
Holger Just Avatar answered Sep 18 '22 20:09

Holger Just


to share the same layout, you can point sinatra to the folder where the layout is in your rails app: (taken from here: http://www.sinatrarb.com/configuration.html)

:views - view template directory A string specifying the directory where view templates are located. By default, this is assumed to be a directory named “views” within the application’s root directory (see the :root setting). The best way to specify an alternative directory name within the root of the application is to use a deferred value that references the :root setting:

  set :views, Proc.new { File.join(root, "templates") } 

From your Rails app you can build a method which you can call from the action where the sinatra app should be included in the view. (given you want to use the index action for this)

def index   @sinatra_content = get_sinatra end # use @sinatra_content in your views for rendering  def get_sinatra    sinatra_ip = 127.0.0.1;    sinatra_port = 4567;    #start a request here    RestClient.get 'http://#{sinatra_ip}:{sinatra_port}/', {:params => {:id => 50, 'foo' => 'bar'}} end 

see how rest-client works here: https://github.com/archiloque/rest-client and don't forget to include the gem in your rails app.

To use links in your sinatra app you should decide if sinatra should handle this (point to sinatra app (with port) or build links in your sinatra app which are handled by your rails app)

like image 20
ben Avatar answered Sep 19 '22 20:09

ben