class Rails::Engine


config.railties_order = [Blog::Engine, :main_app, :all]
# load Blog::Engine with highest priority, followed by application and other railties
Example:
related to engine or application.
It will affect the priority of loading views, helpers, assets and all the other files
In order to change engine’s priority you can use config.railties_order in main application.
== Loading priority
MyEngine::Engine.load_seed
the seeds.rb file. You can load that data using the load_seed method, e.g.
If your engine has migrations, you may also want to prepare data for the database in
migration in the application and rerun copying migrations.
in application. In such a situation you must decide whether to leave that migration or rename the
Note that some of the migrations may be skipped if a migration with the same name already exists
rake ENGINE_NAME:install:migrations
application’s dir:
To use engine’s migrations in application you can use rake task, which copies them to
as in application: db/migrate
Engines can have their own migrations. The default path for migrations is exactly the same
== Migrations & seed data
only helpers defined in the helpers directory will be included.
not include helpers defined in controllers with helper_method or other similar solutions,
It will include all of the helpers from engine’s directory. Take into account that this does
end
helper MyEngine::Engine.helpers
class ApplicationController < ActionController::Base
instance:
If you want to include all of the engine’s helpers, you can use #helpers method on an engine’s
end
helper MyEngine::SharedEngineHelper
class ApplicationController < ActionController::Base
helpers in ApplicationController:
If you want to share just a few specific helpers you can add them to application’s
Sometimes you may want to isolate engine, but use helpers that are defined for it.
== Isolated engine’s helpers
This code will use my_engine.user_path(@user) to generate the proper route.
form_for([my_engine, @user])
attributes for url:
All you need to do is pass the helper as the first element in array with
say that you want to create a form pointing to one of the engine’s routes.
polymorphic_url, you also need to pass the engine helper. Let’s
Finally, if you want to generate a url to an engine’s route using
you can simply omit it.
Note that the :as option given to mount takes the engine_name as default, so most of the time
end
end
end
main_app.foo_path #=> /foo
def index
class BarController
module MyEngine
There is also a main_app helper that gives you access to application’s routes inside Engine:
end
end
my_engine.root_url #=> /my_engine/
def index
class FooController < ApplicationController
Now, you can use the my_engine helper inside your application:
end
match “/foo” => “foo#index”
mount MyEngine::Engine => “/my_engine”, :as => “my_engine”
MyApplication::Application.routes.draw do
# config/routes.rb
created to allow you to do that. Consider such a scenario:
url_helpers inside Application. When you mount an engine in an application’s routes, a special helper is
Since you can now mount an engine inside application’s routes, you do not have direct access to Engine‘s
== Using Engine’s routes outside Engine
to “my_engine_”, changing the MyEngine::Article model to use the my_engine_articles table.
MyEngine::Engine.engine_name will be “my_engine”. It will also set MyEngine.table_name_prefix
Additionally, an isolated engine will set its name according to namespace, so
end
text_field :title # => <input type=“text” name=“article” id=“article_title” />
form_for(MyEngine::Article.new) do
polymorphic_url(MyEngine::Article.new) # => “articles_path”
form fields for convenience.
use the prefix “my_engine”. In an isolated engine, the prefix will be omitted in url helpers and
ActiveModel::Naming. When you use a namespaced model, like MyEngine::Article, it will normally
To make that behavior consistent with other parts of the framework, an isolated engine also has influence on
articles_path as you would do with your application.
need to use longer url helpers like my_engine_articles_path. Instead, you should simply use
The routes above will automatically point to MyEngine::ApplicationController. Furthermore, you don’t
end
resources :articles
MyEngine::Engine.routes.draw do
the namespace is applied by default, so you can ignore it in routes:
your controllers, you also need to do namespace all your routes. With an isolated engine,
The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace
url_helpers from MyEngine::Engine.routes.
If an engine is marked as isolated, FooController has access only to helpers from Engine and
end
end
class FooController < ActionController::Base
module MyEngine
Consider such controller:
the application.
With such an engine, everything that is inside the MyEngine module will be isolated from
end
end
isolate_namespace MyEngine
class Engine < Rails::Engine
module MyEngine
you to pass a module where all your controllers, helpers and models should be nested to:
has its own router. To do that, you simply need to call isolate_namespace. This method requires
However, sometimes you want to isolate your engine from the application, especially if your engine
named routes from the application will be available to your engine’s controllers as well.
as if they were created inside the application itself. This means that all helpers and
Normally when you create controllers, helpers and models inside an engine, they are treated
== Isolated Engine
end
end
engine_name “my_engine”
class Engine < Rails::Engine
module MyEngine
my_engine_engine. You can change it manually using the engine_name method:
Engine name is set by default based on class name. For MyEngine::Engine it will be
my_engine:install:assets
* some of the rake tasks are based on engine name, e.g. my_engine:install:migrations,
it’s used as default :as option
* routes: when you mount an Engine with mount(MyEngine::Engine => '/my_engine'),
There are some places where an Engine’s name is used:
== Engine name
Now, Engine will get only requests that were not handled by Application.
end
mount MyEngine::Engine => “/blog”
match “/blog/omg” => “main#omg”
MyRailsApp::Application.routes.draw do
It’s much better to swap that:
and if there is no such route in Engine‘s routes, it will be dispatched to main#omg.
controller. In such a situation, requests to /blog/omg will go through MyEngine,
MyEngine is mounted at /blog, and /blog/omg points to application’s
end
match “/blog/omg” => “main#omg”
mount MyEngine::Engine => “/blog”
MyRailsApp::Application.routes.draw do
passing requests through many routers. Consider this situation:
Note that now there can be more than one router in your application, and it’s better to avoid
== Mount priority
end
match “/” => “posts#index”
MyEngine::Engine.routes.draw do
# ENGINE/config/routes.rb
endpoint. You can use them just like you use an application’s routes:
If you don’t specify an endpoint, routes will be used as the default
== Routes
end
end
middleware.use SomeMiddleware
class Engine < Rails::Engine
module MyEngine
stack. The usage is exactly the same as in Application:
As an engine can now be a rack endpoint, it can also have a middleware
== Middleware stack
end
mount MyEngine::Engine => “/engine”
MyRailsApp::Application.routes.draw do
Now you can mount your engine in application’s routes just like that:
end
end
endpoint MyRackApplication
class Engine < Rails::Engine
module MyEngine
To do that, use the endpoint method:
you would like to wrap with Engine and provide some of the Engine‘s features.
An engine can be also a rack application. It can be useful if you have a rack application that
== Endpoint
If you have an app/observers folder for example, it will be added by default.
Application, all folders under app are automatically added to the load path.
The Application class adds a couple more paths to this set. And as in your<br><br>end<br>paths # => [“config/routes.rb”]<br>paths # => [“config/locales”]<br>paths # => [“config/initializers”]<br>paths # => [“config”]<br>paths # => [“lib/tasks”]<br>paths # => [“lib”]<br>paths # => [“app/views”]<br>paths # => [“app/models”]<br>paths # => [“app/helpers”]<br>paths # => [“app/controllers”]<br>paths # => [“app”]
class MyEngine < Rails::Engine
The available paths in an engine are:<br><br>end<br>paths << “lib/controllers”
class MyEngine < Rails::Engine
lib/controllers:
You can also have your controllers loaded from both app/controllers and<br><br>end<br>paths = “lib/controllers”
class MyEngine < Rails::Engine
You can set that as an option:
For example, let’s suppose you want to place your controllers in lib/controllers.
which you find convenient.
required to place your controllers at app/controllers, but in any place
opposed to the previous hardcoded path configuration). This means that you are not
Since Rails 3.0, applications and engines have more flexible path configuration (as
== Paths
end
config.app_generators.orm :datamapper
# can pass it to generators method
# note that you can also pass block to app_generators in the same way you
class MyEngine < Rails::Engine
You can also set generators for an application by using config.app_generators:
end
end
g.test_framework :test_unit
g.template_engine :erb
g.orm :active_record
config.generators do |g|
class MyEngine < Rails::Engine
You can set up generators for engines with config.generators method:
== Generators
end
end
app.middleware.use MyEngine::Middleware
initializer “my_engine.add_middleware” do |app|
config.autoload_paths << File.expand_path(“../lib/some/path”, __FILE__)
# Add a load path for this specific Engine
class MyEngine < Rails::Engine
Example:
the current engine.
and autoload_once_paths, which, differently from a Railtie, are scoped to
Rails::Engine you can access autoload_paths, eager_load_paths
Besides the Railtie configuration which is shared across the application, in a
== Configuration
config/locales/*, and load tasks at lib/tasks/*.
inside app, load routes at config/routes.rb, load locales at
(or in your Gemfile) and it will automatically load models, controllers and helpers
Then ensure that this file is loaded at the top of your config/application.rb
end
end
class Engine < Rails::Engine
module MyEngine
# lib/my_engine.rb
your plugin’s lib folder (similar to how we specify a Railtie):
behave as an engine, you have to specify an Engine for it somewhere inside
this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
== Creating an Engine
options that are available in railties can also be used in engines.
methods (like rake_tasks and generators) and configuration
Any Rails::Engine is also a Rails::Railtie, so the same
feature and application sharing.
Rails::Application is just an engine, which allows for simple
functionality and share it with other applications. Since Rails 3.0, every
Rails::Engine allows you to wrap a specific Rails application or subset of

def _all_autoload_once_paths

def _all_autoload_once_paths
  config.autoload_once_paths
end

def _all_autoload_paths

def _all_autoload_paths
  @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
end

def _all_load_paths

def _all_load_paths
  @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
end

def app

def app
  @app ||= begin
    config.middleware = config.middleware.merge_into(default_middleware_stack)
    config.middleware.build(endpoint)
  end
end

def call(env)

def call(env)
  app.call(env.merge!(env_config))
end

def config

def config
  @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
end

def default_middleware_stack

def default_middleware_stack
  ActionDispatch::MiddlewareStack.new
end

def eager_load!

def eager_load!
  railties.all(&:eager_load!)
  config.eager_load_paths.each do |load_path|
    matcher = /\A#{Regexp.escape(load_path)}\/(.*)\.rb\Z/
    Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
      require_dependency file.sub(matcher, '\1')
    end
  end
end

def endpoint(endpoint = nil)

def endpoint(endpoint = nil)
  @endpoint ||= nil
  @endpoint = endpoint if endpoint
  @endpoint
end

def endpoint

def endpoint
  self.class.endpoint || routes
end

def env_config

def env_config
  @env_config ||= {
    'action_dispatch.routes' => routes
  }
end

def find(path)

Finds engine with given path
def find(path)
  expanded_path = File.expand_path path.to_s
  Rails::Engine::Railties.engines.find { |engine|
    File.expand_path(engine.root.to_s) == expanded_path
  }
end

def find_root_with_flag(flag, default=nil)

def find_root_with_flag(flag, default=nil)
  root_path = self.class.called_from
  while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
    parent = File.dirname(root_path)
    root_path = parent != root_path && parent
  end
  root = File.exist?("#{root_path}/#{flag}") ? root_path : default
  raise "Could not find root path for #{self}" unless root
  RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ?
    Pathname.new(root).expand_path : Pathname.new(root).realpath
end

def has_migrations?

def has_migrations?
  paths["db/migrate"].existent.any?
end

def helpers

def helpers
  @helpers ||= begin
    helpers = Module.new
    all = ActionController::Base.all_helpers_from_path(helpers_paths)
    ActionController::Base.modules_for_helpers(all).each do |mod|
      helpers.send(:include, mod)
    end
    helpers
  end
end

def helpers_paths

def helpers_paths
  paths["app/helpers"].existent
end

def inherited(base)

def inherited(base)
  unless base.abstract_railtie?
    base.called_from = begin
      # Remove the line number from backtraces making sure we don't leave anything behind
      call_stack = caller.map { |p| p.sub(/:\d+.*/, '') }
      File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
    end
  end
  super
end

def initialize_generators

def initialize_generators
  require "rails/generators"
end

def initializers

def initializers
  initializers = []
  ordered_railties.each do |r|
    if r == self
      initializers += super
    else
      initializers += r.initializers
    end
  end
  initializers
end

def isolate_namespace(mod)

def isolate_namespace(mod)
  engine_name(generate_railtie_name(mod))
  self.routes.default_scope = { :module => ActiveSupport::Inflector.underscore(mod.name) }
  self.isolated = true
  unless mod.respond_to?(:railtie_namespace)
    name, railtie = engine_name, self
    mod.singleton_class.instance_eval do
      define_method(:railtie_namespace) { railtie }
      unless mod.respond_to?(:table_name_prefix)
        define_method(:table_name_prefix) { "#{name}_" }
      end
      unless mod.respond_to?(:use_relative_model_naming?)
        class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
      end
      unless mod.respond_to?(:railtie_helpers_paths)
        define_method(:railtie_helpers_paths) { railtie.helpers_paths }
      end
      unless mod.respond_to?(:railtie_routes_url_helpers)
        define_method(:railtie_routes_url_helpers) { railtie.routes_url_helpers }
      end
    end
  end
end

def load_console(app=self)

def load_console(app=self)
  railties.all { |r| r.load_console(app) }
  super
end

def load_generators(app=self)

def load_generators(app=self)
  initialize_generators
  railties.all { |r| r.load_generators(app) }
  Rails::Generators.configure!(app.config.generators)
  super
  self
end

def load_runner(app=self)

def load_runner(app=self)
  railties.all { |r| r.load_runner(app) }
  super
end

def load_seed

Blog::Engine.load_seed

seeds, e.g.:
Load data from db/seeds.rb file. It can be used in to load engines'
def load_seed
  seed_file = paths["db/seeds"].existent.first
  load(seed_file) if seed_file
end

def load_tasks(app=self)

def load_tasks(app=self)
  railties.all { |r| r.load_tasks(app) }
  super
  paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
end

def ordered_railties

def ordered_railties
  railties.all + [self]
end

def railties

def railties
  @railties ||= self.class::Railties.new(config)
end

def routes

def routes
  @routes ||= ActionDispatch::Routing::RouteSet.new
  @routes.append(&Proc.new) if block_given?
  @routes
end

def routes?

def routes?
  defined?(@routes)
end

def routes_url_helpers

def routes_url_helpers
  routes.url_helpers
end