Rails::Engine allows you to wrap a specific Rails application or subset of functionality and share it with other applications. Since Rails 3.0, every Rails::Application is just an engine, which allows for simple feature and application sharing.

Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and generators) and configuration options that are available in railties can also be used in engines.

Creating an Engine

In Rails versions prior to 3.0, your gems automatically behaved as engines, however, this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically behave as an engine, you have to specify an Engine for it somewhere inside your plugin’s lib folder (similar to how we specify a Railtie):

  # lib/my_engine.rb
  module MyEngine
    class Engine < Rails::Engine
    end
  end

Then ensure that this file is loaded at the top of your config/application.rb (or in your Gemfile) and it will automatically load models, controllers and helpers inside app, load routes at config/routes.rb, load locales at config/locales/*, and load tasks at lib/tasks/*.

Configuration

Besides the Railtie configuration which is shared across the application, in a Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths, which, differently from a Railtie, are scoped to the current engine.

Example:

  class MyEngine < Rails::Engine
    # Add a load path for this specific Engine
    config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)

    initializer "my_engine.add_middleware" do |app|
      app.middleware.use MyEngine::Middleware
    end
  end

Generators

You can set up generators for engines with config.generators method:

  class MyEngine < Rails::Engine
    config.generators do |g|
      g.orm             :active_record
      g.template_engine :erb
      g.test_framework  :test_unit
    end
  end

You can also set generators for an application by using config.app_generators:

  class MyEngine < Rails::Engine
    # note that you can also pass block to app_generators in the same way you
    # can pass it to generators method
    config.app_generators.orm :datamapper
  end

Paths

Since Rails 3.0, applications and engines have more flexible path configuration (as opposed to the previous hardcoded path configuration). This means that you are not required to place your controllers at app/controllers, but in any place which you find convenient.

For example, let’s suppose you want to place your controllers in lib/controllers. You can set that as an option:

  class MyEngine < Rails::Engine
    paths["app/controllers"] = "lib/controllers"
  end

You can also have your controllers loaded from both app/controllers and lib/controllers:

  class MyEngine < Rails::Engine
    paths["app/controllers"] << "lib/controllers"
  end

The available paths in an engine are:

  class MyEngine < Rails::Engine
    paths["app"]                 # => ["app"]
    paths["app/controllers"]     # => ["app/controllers"]
    paths["app/helpers"]         # => ["app/helpers"]
    paths["app/models"]          # => ["app/models"]
    paths["app/views"]           # => ["app/views"]
    paths["lib"]                 # => ["lib"]
    paths["lib/tasks"]           # => ["lib/tasks"]
    paths["config"]              # => ["config"]
    paths["config/initializers"] # => ["config/initializers"]
    paths["config/locales"]      # => ["config/locales"]
    paths["config/routes"]       # => ["config/routes.rb"]
  end

The Application class adds a couple more paths to this set. And as in your Application, all folders under app are automatically added to the load path. If you have an app/observers folder for example, it will be added by default.

Endpoint

An engine can be also a rack application. It can be useful if you have a rack application that you would like to wrap with Engine and provide some of the Engine’s features.

To do that, use the endpoint method:

  module MyEngine
    class Engine < Rails::Engine
      endpoint MyRackApplication
    end
  end

Now you can mount your engine in application’s routes just like that:

  MyRailsApp::Application.routes.draw do
    mount MyEngine::Engine => "/engine"
  end

Middleware stack

As an engine can now be a rack endpoint, it can also have a middleware stack. The usage is exactly the same as in Application:

  module MyEngine
    class Engine < Rails::Engine
      middleware.use SomeMiddleware
    end
  end

Routes

If you don’t specify an endpoint, routes will be used as the default endpoint. You can use them just like you use an application’s routes:

  # ENGINE/config/routes.rb
  MyEngine::Engine.routes.draw do
    match "/" => "posts#index"
  end

Mount priority

Note that now there can be more than one router in your application, and it’s better to avoid passing requests through many routers. Consider this situation:

  MyRailsApp::Application.routes.draw do
    mount MyEngine::Engine => "/blog"
    match "/blog/omg" => "main#omg"
  end

MyEngine is mounted at /blog, and /blog/omg points to application’s controller. In such a situation, requests to /blog/omg will go through MyEngine, and if there is no such route in Engine’s routes, it will be dispatched to mainomg. It’s much better to swap that:

  MyRailsApp::Application.routes.draw do
    match "/blog/omg" => "main#omg"
    mount MyEngine::Engine => "/blog"
  end

Now, Engine will get only requests that were not handled by Application.

Engine name

There are some places where an Engine’s name is used:

  • routes: when you mount an Engine with mount(MyEngine::Engine => '/my_engine'), it’s used as default :as option
  • some of the rake tasks are based on engine name, e.g. my_engine:install:migrations, my_engine:install:assets

Engine name is set by default based on class name. For MyEngine::Engine it will be my_engine_engine. You can change it manually using the engine_name method:

  module MyEngine
    class Engine < Rails::Engine
      engine_name "my_engine"
    end
  end

Isolated Engine

Normally when you create controllers, helpers and models inside an engine, they are treated as if they were created inside the application itself. This means that all helpers and named routes from the application will be available to your engine’s controllers as well.

However, sometimes you want to isolate your engine from the application, especially if your engine has its own router. To do that, you simply need to call isolate_namespace. This method requires you to pass a module where all your controllers, helpers and models should be nested to:

  module MyEngine
    class Engine < Rails::Engine
      isolate_namespace MyEngine
    end
  end

With such an engine, everything that is inside the MyEngine module will be isolated from the application.

Consider such controller:

  module MyEngine
    class FooController < ActionController::Base
    end
  end

If an engine is marked as isolated, FooController has access only to helpers from Engine and url_helpers from MyEngine::Engine.routes.

The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace your controllers, you also need to do namespace all your routes. With an isolated engine, the namespace is applied by default, so you can ignore it in routes:

  MyEngine::Engine.routes.draw do
    resources :articles
  end

The routes above will automatically point to MyEngine::ApplicationController. Furthermore, you don’t need to use longer url helpers like my_engine_articles_path. Instead, you should simply use articles_path as you would do with your application.

To make that behavior consistent with other parts of the framework, an isolated engine also has influence on ActiveModel::Naming. When you use a namespaced model, like MyEngine::Article, it will normally use the prefix “my_engine“. In an isolated engine, the prefix will be omitted in url helpers and form fields for convenience.

  polymorphic_url(MyEngine::Article.new) # => "articles_path"

  form_for(MyEngine::Article.new) do
    text_field :title # => <input type="text" name="article[title]" id="article_title" />
  end

Additionally, an isolated engine will set its name according to namespace, so MyEngine::Engine.engine_name will be “my_engine“. It will also set MyEngine.table_name_prefix to “my_engine_“, changing the MyEngine::Article model to use the my_engine_articles table.

Using Engine’s routes outside Engine

Since you can now mount an engine inside application’s routes, you do not have direct access to Engine’s url_helpers inside Application. When you mount an engine in an application’s routes, a special helper is created to allow you to do that. Consider such a scenario:

  # config/routes.rb
  MyApplication::Application.routes.draw do
    mount MyEngine::Engine => "/my_engine", :as => "my_engine"
    match "/foo" => "foo#index"
  end

Now, you can use the my_engine helper inside your application:

  class FooController < ApplicationController
    def index
      my_engine.root_url #=> /my_engine/
    end
  end

There is also a main_app helper that gives you access to application’s routes inside Engine:

  module MyEngine
    class BarController
      def index
        main_app.foo_path #=> /foo
      end
    end
  end

Note that the :as option given to mount takes the engine_name as default, so most of the time you can simply omit it.

Finally, if you want to generate a url to an engine’s route using polymorphic_url, you also need to pass the engine helper. Let’s say that you want to create a form pointing to one of the engine’s routes. All you need to do is pass the helper as the first element in array with attributes for url:

  form_for([my_engine, @user])

This code will use my_engine.user_path(@user) to generate the proper route.

Isolated engine’s helpers

Sometimes you may want to isolate engine, but use helpers that are defined for it. If you want to share just a few specific helpers you can add them to application’s helpers in ApplicationController:

  class ApplicationController < ActionController::Base
    helper MyEngine::SharedEngineHelper
  end

If you want to include all of the engine’s helpers, you can use helpers method on an engine’s instance:

  class ApplicationController < ActionController::Base
    helper MyEngine::Engine.helpers
  end

It will include all of the helpers from engine’s directory. Take into account that this does not include helpers defined in controllers with helper_method or other similar solutions, only helpers defined in the helpers directory will be included.

Migrations & seed data

Engines can have their own migrations. The default path for migrations is exactly the same as in application: db/migrate

To use engine’s migrations in application you can use rake task, which copies them to application’s dir:

  rake ENGINE_NAME:install:migrations

Note that some of the migrations may be skipped if a migration with the same name already exists in application. In such a situation you must decide whether to leave that migration or rename the migration in the application and rerun copying migrations.

If your engine has migrations, you may also want to prepare data for the database in the seeds.rb file. You can load that data using the load_seed method, e.g.

  MyEngine::Engine.load_seed

Loading priority

In order to change engine’s priority you can use config.railties_order in main application. It will affect the priority of loading views, helpers, assets and all the other files related to engine or application.

Example:

  # load Blog::Engine with highest priority, followed by application and other railties
  config.railties_order = [Blog::Engine, :main_app, :all]
Methods
#
A
C
D
E
F
H
I
L
O
R
Classes and Modules
Attributes
[RW] called_from
[RW] isolated
Class Public methods
endpoint(endpoint = nil)
     # File railties/lib/rails/engine.rb, line 373
373:       def endpoint(endpoint = nil)
374:         @endpoint ||= nil
375:         @endpoint = endpoint if endpoint
376:         @endpoint
377:       end
find(path)

Finds engine with given path

     # File railties/lib/rails/engine.rb, line 411
411:       def find(path)
412:         expanded_path = File.expand_path path.to_s
413:         Rails::Engine::Railties.engines.find { |engine|
414:           File.expand_path(engine.root.to_s) == expanded_path
415:         }
416:       end
inherited(base)
     # File railties/lib/rails/engine.rb, line 361
361:       def inherited(base)
362:         unless base.abstract_railtie?
363:           base.called_from = begin
364:             # Remove the line number from backtraces making sure we don't leave anything behind
365:             call_stack = caller.map { |p| p.sub(/:\d+.*/, '') }
366:             File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
367:           end
368:         end
369: 
370:         super
371:       end
isolate_namespace(mod)
     # File railties/lib/rails/engine.rb, line 379
379:       def isolate_namespace(mod)
380:         engine_name(generate_railtie_name(mod))
381: 
382:         self.routes.default_scope = { :module => ActiveSupport::Inflector.underscore(mod.name) }
383:         self.isolated = true
384: 
385:         unless mod.respond_to?(:railtie_namespace)
386:           name, railtie = engine_name, self
387: 
388:           mod.singleton_class.instance_eval do
389:             define_method(:railtie_namespace) { railtie }
390: 
391:             unless mod.respond_to?(:table_name_prefix)
392:               define_method(:table_name_prefix) { "#{name}_" }
393:             end
394: 
395:             unless mod.respond_to?(:use_relative_model_naming?)
396:               class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
397:             end
398: 
399:             unless mod.respond_to?(:railtie_helpers_paths)
400:               define_method(:railtie_helpers_paths) { railtie.helpers_paths }
401:             end
402: 
403:             unless mod.respond_to?(:railtie_routes_url_helpers)
404:               define_method(:railtie_routes_url_helpers) { railtie.routes_url_helpers }
405:             end
406:           end
407:         end
408:       end
Instance Public methods
app()
     # File railties/lib/rails/engine.rb, line 467
467:     def app
468:       @app ||= begin
469:         config.middleware = config.middleware.merge_into(default_middleware_stack)
470:         config.middleware.build(endpoint)
471:       end
472:     end
call(env)
     # File railties/lib/rails/engine.rb, line 478
478:     def call(env)
479:       app.call(env.merge!(env_config))
480:     end
config()
     # File railties/lib/rails/engine.rb, line 510
510:     def config
511:       @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
512:     end
eager_load!()
     # File railties/lib/rails/engine.rb, line 433
433:     def eager_load!
434:       railties.all(&:eager_load!)
435: 
436:       config.eager_load_paths.each do |load_path|
437:         matcher = /\A#{Regexp.escape(load_path)}\/(.*)\.rb\Z/
438:         Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
439:           require_dependency file.sub(matcher, '\1')
440:         end
441:       end
442:     end
endpoint()
     # File railties/lib/rails/engine.rb, line 474
474:     def endpoint
475:       self.class.endpoint || routes
476:     end
env_config()
     # File railties/lib/rails/engine.rb, line 482
482:     def env_config
483:       @env_config ||= {
484:         'action_dispatch.routes' => routes
485:       }
486:     end
helpers()
     # File railties/lib/rails/engine.rb, line 448
448:     def helpers
449:       @helpers ||= begin
450:         helpers = Module.new
451:         all = ActionController::Base.all_helpers_from_path(helpers_paths)
452:         ActionController::Base.modules_for_helpers(all).each do |mod|
453:           helpers.send(:include, mod)
454:         end
455:         helpers
456:       end
457:     end
helpers_paths()
     # File railties/lib/rails/engine.rb, line 459
459:     def helpers_paths
460:       paths["app/helpers"].existent
461:     end
initializers()
     # File railties/lib/rails/engine.rb, line 498
498:     def initializers
499:       initializers = []
500:       ordered_railties.each do |r|
501:         if r == self
502:           initializers += super
503:         else
504:           initializers += r.initializers
505:         end
506:       end
507:       initializers
508:     end
load_console(app=self)
     # File railties/lib/rails/engine.rb, line 428
428:     def load_console(app=self)
429:       railties.all { |r| r.load_console(app) }
430:       super
431:     end
load_generators(app=self)
     # File railties/lib/rails/engine.rb, line 348
348:     def load_generators(app=self)
349:       initialize_generators
350:       railties.all { |r| r.load_generators(app) }
351:       Rails::Generators.configure!(app.config.generators)
352:       super
353:       self
354:     end
load_seed()

Load data from db/seeds.rb file. It can be used in to load engines’ seeds, e.g.:

Blog::Engine.load_seed

     # File railties/lib/rails/engine.rb, line 518
518:     def load_seed
519:       seed_file = paths["db/seeds"].existent.first
520:       load(seed_file) if seed_file
521:     end
load_tasks(app=self)
     # File railties/lib/rails/engine.rb, line 422
422:     def load_tasks(app=self)
423:       railties.all { |r| r.load_tasks(app) }
424:       super
425:       paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
426:     end
ordered_railties()
     # File railties/lib/rails/engine.rb, line 494
494:     def ordered_railties
495:       railties.all + [self]
496:     end
railties()
     # File railties/lib/rails/engine.rb, line 444
444:     def railties
445:       @railties ||= self.class::Railties.new(config)
446:     end
routes()
     # File railties/lib/rails/engine.rb, line 488
488:     def routes
489:       @routes ||= ActionDispatch::Routing::RouteSet.new
490:       @routes.append(&Proc.new) if block_given?
491:       @routes
492:     end
routes_url_helpers()
     # File railties/lib/rails/engine.rb, line 463
463:     def routes_url_helpers
464:       routes.url_helpers
465:     end
Instance Protected methods
_all_autoload_once_paths()
     # File railties/lib/rails/engine.rb, line 645
645:     def _all_autoload_once_paths
646:       config.autoload_once_paths
647:     end
_all_autoload_paths()
     # File railties/lib/rails/engine.rb, line 649
649:     def _all_autoload_paths
650:       @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
651:     end
_all_load_paths()
     # File railties/lib/rails/engine.rb, line 653
653:     def _all_load_paths
654:       @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
655:     end
default_middleware_stack()
     # File railties/lib/rails/engine.rb, line 641
641:     def default_middleware_stack
642:       ActionDispatch::MiddlewareStack.new
643:     end
find_root_with_flag(flag, default=nil)
     # File railties/lib/rails/engine.rb, line 626
626:     def find_root_with_flag(flag, default=nil)
627:       root_path = self.class.called_from
628: 
629:       while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
630:         parent = File.dirname(root_path)
631:         root_path = parent != root_path && parent
632:       end
633: 
634:       root = File.exist?("#{root_path}/#{flag}") ? root_path : default
635:       raise "Could not find root path for #{self}" unless root
636: 
637:       RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ?
638:         Pathname.new(root).expand_path : Pathname.new(root).realpath
639:     end
has_migrations?()
     # File railties/lib/rails/engine.rb, line 622
622:     def has_migrations?
623:       paths["db/migrate"].existent.any?
624:     end
initialize_generators()
     # File railties/lib/rails/engine.rb, line 614
614:     def initialize_generators
615:       require "rails/generators"
616:     end
routes?()
     # File railties/lib/rails/engine.rb, line 618
618:     def routes?
619:       defined?(@routes)
620:     end