Rails 3.0: Mount Multiple Apps as Engines

Since last week I have been working on upgrading a major project from Rails 2.3.5 to Rails 3.0.0.beta and also on moving other projects to use the latest version of bundler. Getting all to work was not easy, but this gave me a chance to look into the rails initialization code in detail. Based on this adventure, I tried to convert some plugins into gems and also explored ways of mounting a Rails 3.0 application into another. Here is a very basic example of how you can mount a reusable Rails 3.0 application into a container application. This might not be the best approach for developing multi apps, but it surely offers some fun :).

My setup is Rails 3.0.0.beta with ruby 1.9.1 for this example. If the steps sound confusing, you can follow the example code here http://github.com/railsbob/MyApp.

First of all, lets create a generic, reusable application. My reusable ‘login application’ with one controller is called as ‘Saas’.

To allow sharing of this application by others, we need to wrap it as a Rails::Engine. To do so, add a file named ‘engine.rb’ to config folder.

Create a ‘saas.rb’ in lib folder which requires this engine.rb. This is required, as we want to load the application as Saas::Engine instead of Saas::Application.

Lets create a container app which mounts the Saas Application.

rails MyApp

To mount it, copy the Saas application into lib of MyApp.

Saas application’s routes.rb should be modified to replace Saas::Application by Rails::Application. Also, to keep things modular, add a namespace to the routes.

The next step is to hook Saas app into the initializer process of MyApp. There are many ways to do it, but we will follow the bundler approach.

In MyApp/Gemfile, require the saas application from lib directory as a gem.

At this stage, bundler complains about missing version for saas as it is expecting a gem. So lets add a saas.gemspec at MyApp/lib/saas/saas.gemspec with basic information.

Start the server from the container app and if you go to /saas/sessions you should see the text ‘Hi from SessionsController’.

Note that even if the Saas application was modified to be an engine, it still works as a standalone application when run from its root.
The example code discussed above is available at http://github.com/railsbob/MyApp.
.

2 Comments

RSS feed for comments on this post. TrackBack URL

  1. Remco — March 3, 2010

    Hello, Thanks for sharing this.
    I have one question:
    if I create helpers in the saas application: should it be possible to make these helpers available in the container application? i tried but i wasn’t able to do it. Perhaps you know how to?

    Regards,Remco

  2. Angelo Ashmore — March 17, 2010

    I’ve been looking all over for a way to do this with Rails 3. Thanks for the article!

Leave a comment

Preview: