class Rails::Engine
config.railties_order = [Blog::Engine, :main_app, :all]
# load Blog::Engine with highest priority, followed by application and other railties
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 the main application.
== Loading priority
MyEngine::Engine.load_seed
the db/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 the rake task below, 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 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 the #helper 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
get “/foo” => “foo#index”
mount MyEngine::Engine => “/my_engine”, as: “my_engine”
Rails.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 Enginemy_engine_articles
database table by default.
meaning for example that MyEngine::Article
will use the
“my_engine”. It will also set MyEngine.table_name_prefix
to “my_engine_”,
namespace, so MyEngine::Engine.engine_name
will return
Additionally, an isolated engine will set its own name according to its
end
text_field :title # => <input type=“text” name=“article” id=“article_title” />
form_for(MyEngine::Article.new) do
# => “articles_path” # not “my_engine_articles_path”
polymorphic_url(MyEngine::Article.new)
be omitted in URL helpers and form fields, for convenience.
names with the prefix “namespace”. In an isolated engine, the prefix willNamespace::Article
, ActiveModel::Naming will generate
normal Rails app, when you use a namespaced model such as
isolated engines also have an effect on ActiveModel::Naming. In a
To make this behavior consistent with other parts of the framework,articles_path
, like you would do with your main application.
URL helpers like my_engine_articles_path
. Instead, you should simply useMyEngine::ArticlesController
. You also don’t need to use longer
If MyEngine
is isolated, the routes above will point to
end
resources :articles
MyEngine::Engine.routes.draw do
routes:
automatically applied, so you don’t need to specify it explicitly in your
the related routes. With an isolated engine, the engine’s namespace is
Normally, when you namespace your controllers, you also need to namespace
The next thing that changes in isolated engines is the behavior of routes.MyEngine::Engine.routes
.
access to helpers from MyEngine
, and url_helpers
from
If the MyEngine
engine is marked as isolated, FooController
only has
end
end
class FooController < ActionController::Base
module MyEngine
Consider this 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 MyEnginemy_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
* rake task for installing migrations 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”
get “/blog/omg” => “main#omg”
Rails.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
get “/blog/omg” => “main#omg”
mount MyEngine::Engine => “/blog”
Rails.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
get “/” => “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”
Rails.application.routes.draw do
Now you can mount your engine in application’s routes:
end
end
endpoint MyRackApplication
class Engine < Rails::Engine
module MyEngine
To do that, use the endpoint
method:
you would like to provide with some of the Engine
‘s features.
An engine can also be a Rack application. It can be useful if you have a Rack application that
== Endpoint
If you have an app/services
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::Enginelib/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
.
in any place which you find convenient.
are not required to place your controllers at app/controllers
, but
Applications and engines have flexible path configuration, meaning that you
== 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”, __dir__)
# Add a load path for this specific Engine
class MyEngine < Rails::Engineautoload_once_paths
settings which are scoped to that engine.
Additionally, each engine can access autoload_paths
, eager_load_paths
and
all railties and the application.
Like railties, engines can access a config object which contains configuration shared by
== Configurationconfig/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
specify a Railtie
):
for it somewhere inside your plugin’s lib
folder (similar to how we
If you want a gem to behave as an engine, you have to specify an Engine
== 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.
Every Rails::Application is just an engine, which allows for simple
functionality and share it with other applications or within a larger packaged application.Rails::Engine
allows you to wrap a specific Rails application or subset of
def self.find_root_with_flag(flag, root_path, default = nil) # :nodoc:
def self.find_root_with_flag(flag, root_path, default = nil) # :nodoc: 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 Pathname.new File.realpath root end
def _all_autoload_once_paths
def _all_autoload_once_paths config.autoload_once_paths.uniq end
def _all_autoload_paths
def _all_autoload_paths @_all_autoload_paths ||= begin autoload_paths = config.autoload_paths autoload_paths += config.eager_load_paths autoload_paths -= config.autoload_once_paths autoload_paths.uniq end end
def _all_load_paths(add_autoload_paths_to_load_path)
def _all_load_paths(add_autoload_paths_to_load_path) @_all_load_paths ||= begin load_paths = config.paths.load_paths if add_autoload_paths_to_load_path load_paths += _all_autoload_paths load_paths += _all_autoload_once_paths end load_paths.uniq end end
def app
def app @app || @app_build_lock.synchronize { @app ||= begin stack = default_middleware_stack config.middleware = build_middleware.merge_into(stack) config.middleware.build(endpoint) end } end
def build_middleware
def build_middleware config.middleware end
def build_request(env)
def build_request(env) env.merge!(env_config) req = ActionDispatch::Request.new env req.routes = routes req.engine_script_name = req.script_name req end
def call(env)
def call(env) req = build_request env app.call req.env end
def config
def config @config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from)) end
def default_middleware_stack
def default_middleware_stack ActionDispatch::MiddlewareStack.new end
def eager_load!
def eager_load! # Already done by Zeitwerk::Loader.eager_load_all. By now, we leave the # method as a no-op for backwards compatibility. end
def endpoint(endpoint = nil)
def endpoint(endpoint = nil) @endpoint ||= nil @endpoint = endpoint if endpoint @endpoint end
def endpoint
Returns the endpoint for this engine. If none is registered,
def endpoint self.class.endpoint || routes end
def env_config
def env_config @env_config ||= {} end
def find(path)
def find(path) expanded_path = File.expand_path path Rails::Engine.subclasses.each do |klass| engine = klass.instance return engine if File.expand_path(engine.root) == expanded_path end nil end
def find_root(from)
def find_root(from) find_root_with_flag "lib", from 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.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? Rails::Railtie::Configuration.eager_load_namespaces << base base.called_from = begin call_stack = caller_locations.map { |l| l.absolute_path || l.path } File.dirname(call_stack.detect { |p| !p.match?(%r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack]) }) end end super end
def initialize
def initialize @_all_autoload_paths = nil @_all_load_paths = nil @app = nil @config = nil @env_config = nil @helpers = nil @routes = nil @app_build_lock = Mutex.new super end
def isolate_namespace(mod)
def isolate_namespace(mod) engine_name(generate_railtie_name(mod.name)) 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) { |include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) } end end end end
def load_config_initializer(initializer) # :doc:
def load_config_initializer(initializer) # :doc: ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do load(initializer) end end
def load_console(app = self)
Load console and invoke the registered hooks.
def load_console(app = self) require "rails/console/app" require "rails/console/helpers" run_console_blocks(app) self end
def load_generators(app = self)
Load Rails generators and invoke the registered hooks.
def load_generators(app = self) require "rails/generators" run_generators_blocks(app) Rails::Generators.configure!(app.config.generators) self end
def load_runner(app = self)
Load Rails runner and invoke the registered hooks.
def load_runner(app = self) run_runner_blocks(app) self end
def 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.rb"].existent.first run_callbacks(:load_seed) { load(seed_file) } if seed_file end
def load_server(app = self)
Invoke the server registered hooks.
def load_server(app = self) run_server_blocks(app) self end
def load_tasks(app = self)
Load Rake and railties tasks, and invoke the registered hooks.
def load_tasks(app = self) require "rake" run_tasks_blocks(app) self end
def railties
def railties @railties ||= Railties.new end
def routes(&block)
Defines the routes for this engine. If a block is given to
def routes(&block) @routes ||= ActionDispatch::Routing::RouteSet.new_with_config(config) @routes.append(&block) if block_given? @routes end
def routes? # :nodoc:
def routes? # :nodoc: @routes end
def run_tasks_blocks(*) # :nodoc:
def run_tasks_blocks(*) # :nodoc: super paths["lib/tasks"].existent.sort.each { |ext| load(ext) } end