Rails::Engine
允许你包装一个特定的 Rails 应用程序或功能子集,并与其他应用程序或更大的打包应用程序共享。每个 Rails::Application
都只是一个引擎,它允许简单的功能和应用程序共享。
任何 Rails::Engine
也是一个 Rails::Railtie
,因此 railties 中可用的相同方法(如 rake_tasks 和 generators)和配置选项也可以在引擎中使用。
创建 Engine
如果你希望一个 gem 以引擎的形式运行,你必须在插件的 lib
文件夹中的某个地方为它指定一个 Engine
(类似于我们指定 Railtie
的方式)
# lib/my_engine.rb
module MyEngine
class Engine < Rails::Engine
end
end
然后确保在 config/application.rb
(或在你的 Gemfile
)中加载此文件,它将自动加载 app
中的模型、控制器和帮助器,在 config/routes.rb
中加载路由,在 config/locales/*/
中加载区域设置,并在 lib/tasks/*/
中加载任务。
配置
与 railties 一样,引擎可以访问包含所有 railties 和应用程序共享的配置的 config 对象。此外,每个引擎还可以访问作用域限定到该引擎的 autoload_paths
、eager_load_paths
和 autoload_once_paths
设置。
class MyEngine < Rails::Engine
# Add a load path for this specific Engine
config.autoload_paths << File.expand_path("lib/some/path", __dir__)
initializer "my_engine.add_middleware" do |app|
app.middleware.use MyEngine::Middleware
end
end
生成器
你可以使用 config.generators
方法为引擎设置生成器
class MyEngine < Rails::Engine
config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :test_unit
end
end
你还可以使用 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
路径
应用程序和引擎具有灵活的路径配置,这意味着你不需要将控制器放在 app/controllers
中,而可以放在你认为方便的任何地方。
例如,假设你希望将控制器放在 lib/controllers
中。你可以将它设置为一个选项
class MyEngine < Rails::Engine
paths["app/controllers"] = "lib/controllers"
end
你也可以从 app/controllers
和 lib/controllers
加载控制器
class MyEngine < Rails::Engine
paths["app/controllers"] << "lib/controllers"
end
引擎中可用的路径是
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.rb"] # => ["config/routes.rb"]
end
Application
类向此集合添加了更多路径。并且与你的 Application
中一样,app
下的所有文件夹都会自动添加到加载路径。例如,如果你有一个 app/services
文件夹,它将默认添加。
端点
引擎还可以是一个 Rack
应用程序。如果你有一个 Rack
应用程序,并且希望为其提供一些 Engine
的功能,这会很有用。
要做到这一点,请使用 ::endpoint
方法
module MyEngine
class Engine < Rails::Engine
endpoint MyRackApplication
end
end
现在,你可以在应用程序的路由中挂载你的引擎
Rails.application.routes.draw do
mount MyEngine::Engine => "/engine"
end
中间件堆栈
由于引擎现在可以成为一个 Rack
端点,因此它也可以有一个中间件堆栈。其用法与 Application
中完全相同
module MyEngine
class Engine < Rails::Engine
middleware.use SomeMiddleware
end
end
路由
如果你没有指定端点,则路由将被用作默认端点。你可以像使用应用程序的路由一样使用它们
# ENGINE/config/routes.rb
MyEngine::Engine.routes.draw do
get "/" => "posts#index"
end
挂载优先级
请注意,现在你的应用程序中可以有多个路由器,最好避免通过许多路由器传递请求。考虑这种情况
Rails.application.routes.draw do
mount MyEngine::Engine => "/blog"
get "/blog/omg" => "main#omg"
end
MyEngine
挂载在 /blog
,而 /blog/omg
指向应用程序的控制器。在这种情况下,对 /blog/omg
的请求将通过 MyEngine
,如果 Engine
的路由中没有这样的路由,它将被分派到 main#omg
。交换它们会好得多
Rails.application.routes.draw do
get "/blog/omg" => "main#omg"
mount MyEngine::Engine => "/blog"
end
现在,Engine
将只获取 Application
未处理的请求。
Engine
名称
有一些地方使用了引擎的名称
-
路由:当你使用
mount(MyEngine::Engine => '/my_engine')
挂载一个Engine
时,它被用作默认的:as
选项 -
用于安装迁移的 rake 任务
my_engine:install:migrations
Engine
名称默认根据类名设置。对于 MyEngine::Engine
,它将是 my_engine_engine
。你可以使用 engine_name
方法手动更改它
module MyEngine
class Engine < Rails::Engine
engine_name "my_engine"
end
end
隔离的 Engine
通常,当你在一个引擎内创建控制器、帮助器和模型时,它们会被视为在应用程序本身内创建的。这意味着应用程序中的所有帮助器和命名路由也将对你的引擎的控制器可用。
但是,有时你希望将你的引擎与应用程序隔离,特别是如果你的引擎有自己的路由器。要做到这一点,你只需调用 ::isolate_namespace
。此方法要求你传递一个模块,其中应嵌套你的所有控制器、帮助器和模型
module MyEngine
class Engine < Rails::Engine
isolate_namespace MyEngine
end
end
对于这样的引擎,MyEngine
模块中的所有内容都将与应用程序隔离。
考虑这个控制器
module MyEngine
class FooController < ActionController::Base
end
end
如果 MyEngine
引擎被标记为隔离,FooController
只能访问 MyEngine
中的帮助器,以及 MyEngine::Engine.routes
中的 url_helpers
。
隔离引擎中发生变化的另一件事是路由的行为。通常,当您对控制器进行命名空间划分时,还需要对相关路由进行命名空间划分。使用隔离引擎,引擎的命名空间会自动应用,因此您无需在路由中明确指定它
MyEngine::Engine.routes.draw do
resources :articles
end
如果 MyEngine
被隔离,则上述路由将指向 MyEngine::ArticlesController
。您也不需要使用较长的 URL 帮助器,如 my_engine_articles_path
。相反,您应该只使用 articles_path
,就像您对主应用程序所做的那样。
为了使此行为与框架的其他部分保持一致,隔离引擎还会对 ActiveModel::Naming
产生影响。在普通的 Rails 应用程序中,当您使用命名空间模型(如 Namespace::Article
)时,ActiveModel::Naming
将生成带有前缀“namespace”的名称。在隔离引擎中,为了方便,前缀将在 URL 帮助器和表单字段中省略。
polymorphic_url(MyEngine::Article.new)
# => "articles_path" # not "my_engine_articles_path"
form_for(MyEngine::Article.new) do
text_field :title # => <input type="text" name="article[title]" id="article_title" />
end
此外,隔离引擎会根据其命名空间设置自己的名称,因此 MyEngine::Engine.engine_name
将返回“my_engine”。它还将 MyEngine.table_name_prefix
设置为“my_engine_”,这意味着例如 MyEngine::Article
将默认使用 my_engine_articles
数据库表。
在 Engine
外部使用引擎的路由
由于您现在可以在应用程序的路由中挂载引擎,因此您无法在 Application
中直接访问 Engine
的 url_helpers
。当您在应用程序的路由中挂载引擎时,将创建一个特殊的帮助器来允许您执行此操作。考虑以下情况
# config/routes.rb
Rails.application.routes.draw do
mount MyEngine::Engine => "/my_engine", as: "my_engine"
get "/foo" => "foo#index"
end
现在,您可以在应用程序中使用 my_engine
帮助器
class FooController < ApplicationController
def index
my_engine.root_url # => /my_engine/
end
end
还有一个 main_app
帮助器,它允许您在引擎中访问应用程序的路由
module MyEngine
class BarController
def index
main_app.foo_path # => /foo
end
end
end
请注意,提供给挂载的 :as
选项将 engine_name
作为默认值,因此大多数情况下您只需省略它即可。
最后,如果您想使用 polymorphic_url
生成指向引擎路由的 URL,您还需要传递引擎帮助器。假设您想创建一个指向引擎的某个路由的表单。您需要做的就是将帮助器作为 URL 属性数组中的第一个元素传递
form_for([my_engine, @user])
此代码将使用 my_engine.user_path(@user)
生成正确的路由。
隔离引擎的助手
有时您可能想要隔离一个引擎,但使用为其定义的助手。如果您只想共享几个特定的助手,则可以将它们添加到 ApplicationController 中应用程序的助手。
class ApplicationController < ActionController::Base
helper MyEngine::SharedEngineHelper
end
如果您想包含所有引擎的助手,则可以在引擎实例上使用助手方法
class ApplicationController < ActionController::Base
helper MyEngine::Engine.helpers
end
它将包含引擎目录中的所有助手。请注意,这不包括在控制器中使用 helper_method 或其他类似解决方案定义的助手,只会包含在助手目录中定义的助手。
迁移和种子数据
引擎可以有自己的迁移。迁移的默认路径与应用程序中的路径完全相同:db/migrate
要在应用程序中使用引擎的迁移,可以使用下面的 rake 任务,它会将它们复制到应用程序的目录中
$ rake ENGINE_NAME:install:migrations
请注意,如果应用程序中已存在具有相同名称的迁移,则可能会跳过一些迁移。在这种情况下,您必须决定保留该迁移还是重命名应用程序中的迁移并重新运行复制迁移。
如果您的引擎有迁移,您可能还希望在 db/seeds.rb
文件中为数据库准备数据。您可以使用 load_seed
方法加载该数据,例如
MyEngine::Engine.load_seed
加载优先级
为了更改引擎的优先级,您可以在主应用程序中使用 config.railties_order
。它将影响加载视图、助手、资产以及与引擎或应用程序相关的所有其他文件的优先级。
# load Blog::Engine with highest priority, followed by application and other railties
config.railties_order = [Blog::Engine, :main_app, :all]
- A
- C
- E
- F
- H
- I
- L
- N
- R
属性
[RW] | called_from | |
[RW] | isolated | |
[RW] | isolated? |
类公共方法
endpoint(endpoint = nil) 链接
find(path) 链接
查找给定路径的引擎。
find_root(from) 链接
inherited(base) 链接
# File railties/lib/rails/engine.rb, line 361 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
isolate_namespace(mod) 链接
# File railties/lib/rails/engine.rb, line 385 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}_" } ActiveSupport.on_load(:active_record) do mod.singleton_class.redefine_method(:table_name_prefix) do "#{ActiveRecord::Base.table_name_prefix}#{name}_" end end 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
new() 链接
实例公共方法
call(env) 链接
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 534 def call(env) req = build_request env app.call req.env end
config() 链接
定义引擎的配置对象。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 553 def config @config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from)) end
eager_load!() 链接
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 491 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
endpoint() 链接
返回此引擎的端点。如果没有注册,则默认为 ActionDispatch::Routing::RouteSet。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 529 def endpoint self.class.endpoint || routes end
env_config() 链接
定义每次调用时添加的其他 Rack
env 配置。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 540 def env_config @env_config ||= {} end
helpers() 链接
返回一个包含为引擎定义的所有帮助器的模块。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 501 def helpers @helpers ||= begin helpers = Module.new AbstractController::Helpers.helper_modules_from_paths(helpers_paths).each do |mod| helpers.include(mod) end helpers end end
helpers_paths() 链接
返回所有已注册的帮助器路径。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 512 def helpers_paths paths["app/helpers"].existent end
load_console(app = self) 链接
加载控制台并调用已注册的钩子。有关更多信息,请查看 Rails::Railtie.console
。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 453 def load_console(app = self) require "rails/console/app" require "rails/console/helpers" run_console_blocks(app) self end
load_generators(app = self) 链接
加载 Rails 生成器并调用已注册的钩子。有关更多信息,请查看 Rails::Railtie.generators
。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 477 def load_generators(app = self) require "rails/generators" run_generators_blocks(app) Rails::Generators.configure!(app.config.generators) self end
load_runner(app = self) 链接
加载 Rails runner 并调用已注册的钩子。有关更多信息,请查看 Rails::Railtie.runner
。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 462 def load_runner(app = self) run_runner_blocks(app) self end
load_seed() 链接
从 db/seeds.rb 文件加载数据。它可用于加载引擎的种子,例如:
Blog::Engine.load_seed
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 561 def load_seed seed_file = paths["db/seeds.rb"].existent.first run_callbacks(:load_seed) { load(seed_file) } if seed_file end
load_server(app = self) 链接
调用已注册的服务器钩子。有关更多信息,请查看 Rails::Railtie.server
。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 486 def load_server(app = self) run_server_blocks(app) self end
load_tasks(app = self) 链接
加载 Rake 和 railties 任务,并调用已注册的钩子。有关更多信息,请查看 Rails::Railtie.rake_tasks
。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 469 def load_tasks(app = self) require "rake" run_tasks_blocks(app) self end
railties() 链接
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 496 def railties @railties ||= Railties.new end
routes(&block) 链接
定义此引擎的路由。如果将一个块赋给 routes,它将附加到引擎中。
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 546 def routes(&block) @routes ||= ActionDispatch::Routing::RouteSet.new_with_config(config) @routes.append(&block) if block_given? @routes end
实例私有方法
load_config_initializer(initializer) 链接
来源:显示 | 在 GitHub 上
# File railties/lib/rails/engine.rb, line 688 def load_config_initializer(initializer) # :doc: ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do load(initializer) end end