Rails Engine

Recently, I build some Rails engines. And I found it’s a good way to organize and share reusable code across a number of applications.

Rails Engine is not like Ruby gem. It’s more like a rails app, it has its own controllers, views and migrations. And basically it has two type of engine, full or mountable.

Full vs Mountable Engine

Full Engine

With a full engine, the parent application inherits the routes from the engine. It is not necessary to specify anything in the main_app’s routes.rb. Specifying the gem in Gemfile is enough for the parent app to inherit the models, routes etc. The engine routes are specified as:

1
2
3
4
# my_engine/config/routes.rb
Rails.application.routes.draw do
# whatever
end

No namespacing of models, controllers, etc. These are immediately accessible to the parent application.

Mountable Engine

The engine’s namespace is isolated by default:

1
2
3
4
5
6
# my_engine/lib/my_engine/engine.rb
module MyEngine
class Engine < Rails::Engine
isolate_namespace MyEngine
end
end

With a mountable engine, the routes are namespaced and the parent app can bundle this functionality under a single route:

1
2
3
4
5
6
7
8
9
# my_engine/config/routes.rb
MyEngine::Engine.routes.draw do
#whatever
end
# main_app/config/routes.rb
ParentApp::Application.routes.draw do
mount MyEngine::Engine => "/engine", :as => "namespaced"
end

Models, controllers, etc are isolated from the parent application.

Tips:
--full for the full engine and --mountable for the mountable engine