Rails 5 开发进阶
  • Rails 6 开发进阶
  • Active Model 功能模块
    • Model - 核心
      • Validations
      • Validator
      • Errors
      • Validations 相关的 Callbacks
      • Conversion
      • Naming & Name
      • Translation
      • Lint Tests
    • Model 的增强模块
      • Attribute Assignment
      • Attribute Methods
      • Dirty
      • Secure Password
      • Forbidden Attributes Protection
      • Serialization
      • Callbacks - 快速提供 3 个回调方法
    • 其它
  • Active Record 数据库操作:增删查改
    • Relation
      • Relation 文件下的方法
      • Query Methods
        • Preload, Eagerload, Includes 和 Joins 等
        • Query Methods 读取、设置查询方法
        • 关联表复杂查询示例
      • Spawn Methods
      • Batches 批量查询
      • Finder Methods
      • Calculations 统计计算
      • 其它
    • Collection Proxy
    • Scoping
    • Attribute Methods
      • Attribute Methods 文件下的内容
      • Read & Write
      • Before Type Cast - 类型转换
      • Query - 后缀 '?' 问询
      • Serialization
      • Primary Key
      • 其它
    • Persistence
      • 数据更新方法对比
      • 对比,然后使用合适的方法
      • 多个 save 方法
    • Counter Cache 计数器
    • Querying
    • 其它
  • Active Record 数据库关联关系
    • Associations 文件 - 4 个关联方法
    • Aggregations - composed_of 方法
    • Builder - 功能的实现
      • Association
      • Singular Association
      • Collection Association
      • Has One
      • Belongs To
      • Has Many
      • Has And Belongs To Many
    • Reflection - 实现之关联两者
      • Abstract Reflection
      • Macro Reflection
      • Association Reflection
      • Aggregate Reflection
      • Has Many Reflection
      • Has One Reflection
      • Belongs To Reflection
      • Has And Belongs To Many Reflection
      • Through Reflection
      • Polymorphic Reflection
      • Runtime Reflection
    • Association 目录 - 实现之提供方法
      • Association
      • Belongs To Association
      • Belongs To Polymorphic Association
      • Collection Association
      • Foreign Association
      • Has Many Association
      • Has Many Through Association
      • Has One Association
      • Has One Through Association
      • Singular Association
      • Through Association
    • 4 个关联方法的使用
      • belongs_to
      • has_one
      • has_many
      • has_and_belongs_to_many
      • 关联方法的可选参数汇总
    • 4 个关联方法的补充
      • 使用关联方法后,Rails 自动生成了哪些方法
      • habtm vs has_many through
    • Nested Attributes 嵌套属性
    • Inheritance 单表继承
    • 其它
      • Autosave Association
      • Alias Tracker
      • Association Scope
      • Join Dependency
      • Preloader
      • Association Relation
  • Active Record 数据库特性及功能模块
    • Callbacks 回调
      • 回调及其顺序
      • 跳过回调
      • 可选参数
      • after_create 与 after_commit on create 各自存在的坑
    • Transactions 事务
    • Locking 锁
    • Enum 枚举
    • Store
    • Validations 校验
    • Secure Token
    • Integration
    • No Touching
    • Touch Later
    • Attributes
    • Readonly Attributes
    • Serialization
    • Suppressor
  • Active Record 数据库迁移:表/字段
    • Connection Handling 连接数据库
    • Migration 文件下的内容
      • 控制台里迁移、回滚等命令
      • say_with_time
    • Connection Adapters
      • Schema Statements
        • create_table
        • change_table
      • Table Definition
      • Table
      • Database Statements
    • Model Schema
    • Schema
    • 其它
      • schema_format
      • Schema Migration
  • Active Record 数据库连接:底层适配,约定、配置
    • Naming Conventions
    • Schema Conventions
    • Timestamps
    • Core
      • 获取 record 对象
    • Sanitization
    • Migration DatabaseTasks
    • Statement Cache
    • Collection Cache Key
    • Attribute Mutation Tracker
    • Attribute Decorators
    • 其它
  • Action View 布局、渲染相关
    • Layouts
    • Base - 为渲染打基础
    • 非 Rails 是如何渲染的
    • Rails 是如何渲染的
      • Rendering
    • 渲染器介绍
      • Renderer - 渲染的入口
      • 基类 Abstract Renderer
      • 子类 Template Renderer
      • 子类 Partial Renderer & Collection Caching
      • 子类 Streaming Template Renderer
    • Template 内容
      • template 本文件下的内容
      • template 目录
    • Lookup Context
      • View Paths
      • Details Key & Details Cache
    • view_context
      • Context
      • Output Flow & Streaming Flow
    • View Paths
    • 其它
      • Output Buffer & Streaming Buffer
  • Action View 提供的 Helper 方法
    • 与表单直接相关的辅助方法
      • Form Builder
        • 扩展 Form Builder
      • Form Helper
      • Form Options Helper
      • Form Tag Helper
    • 与表单非直接相关的辅助方法
      • Tag Helper
      • Url Helper
      • Asset Tag Helper
      • Cache Helper
        • 片段缓存和 Cache Key
      • Controller Helper
      • Asset Url Helper
      • Csrf Helper
      • Capture Helper
      • Debug Helper
      • Date Helper
      • JavaScript Helper
      • Number Helper
      • Output Safety Helper
      • Rendering Helper
      • Record Tag Helper
      • Sanitize Helper
      • Translation Helper
      • Text Helper
      • Atom Feed Helper
      • Active Model Instance Tag
    • 其它
  • Action View 其它类和模块
    • Record Identifier
    • Routing Url For
    • Model Naming
    • Digestor
      • Dependency Tracker
    • 其它
  • Action Dispatch Http 作用:请求、响应
    • Request
      • Request 文件下的内容
      • URL
      • Headers
      • Mime Negotiation
      • Parameters
      • Parameter Filter & Filter Parameters
      • Cache 之 Request
      • Uploaded File
      • Utils
    • Response
      • Response 文件下的内容
      • Filter Redirect
      • Cache 之 Response
    • 其它
      • Rack Cache
      • Mime Type register
      • Session
  • Action Dispatch Middleware 中间件
    • Middleware
      • Rack - Ruby Web server 接口
      • 查看项目用了哪些 Middleware
      • 定制 Middleware
      • Middleware Stack
    • 各个 Middleware 类
      • Static
      • SSL
      • Show Exceptions
      • Exception Wrapper
      • Public Exceptions
        • 定制 Public Exceptions
      • Debug Exceptions
      • Request Id
      • Remote Ip
      • Reloader
      • Params Parser
      • Flash
      • Cookies & ChainedCookieJars
      • Session
      • Callbacks
      • Load Interlock
      • Executor
      • Debug Locks
  • Action Dispatch Routing 路由顶层(表现形式)
    • Mapper
      • Base
      • Http Helpers
      • Scoping
        • scope
        • namespace
      • Concerns
      • Resources
      • Scope、Mapping、Constraints
      • Redirection
      • match 和 scope 方法 - 重中之重
      • 路由常用方法汇总
    • 其它
      • Polymorphic Routes
      • Url For
      • Routing 概述:生成、存储、识别
      • 一步步分析从请求到响应涉及到 Rails 的哪些模块
      • endpoint 和 inspector 文件
  • Action Dispatch RouteSet 路由底层(实现方式)
    • 实例对象和各个实例方法
    • Named Route Collection
    • Dispatcher
    • Generator
    • Routes Proxy
    • Journey
  • Abstract Controller
    • Base
      • 获取所有的 Controller 和 action
    • Helpers
    • Callbacks
    • Rendering
    • render 参数汇总与详解
      • 更多关于渲染
    • Translation
    • Collector
    • 其它
      • Asset Paths
      • Routes Helpers
      • Logger
      • Url For
    • Caching
    • Caching & Caching Fragments
      • 默认片段缓存策略
  • Action Controller - Rack 增强扩展
    • Metal - 增强的 Rack, 简陋的 Controller
      • Metal 文件下的内容
      • Middleware Stack
      • Metal 使用举例
    • API - Metal 的继承者
    • Base - Metal 的继承者
    • Metal 的扩展
      • Redirecting
      • Head
      • Conditional Get - HTTP Cache
        • Conditional Get 其它
      • Etag With Template Digest
      • Http Authentication
        • Basic
        • Digest
        • Token
      • Streaming
      • Live
      • Mime Responds & Collector
      • Renderers 增删渲染器
      • Params Wrapper
      • Request Forgery Protection
      • Parameters & Strong Parameters
      • Data Streaming
      • Force SSL
      • Flash
      • Helpers
      • Cookies
      • Implicit Render
      • Instrumentation
      • Rendering
      • Rescue
      • Url For
      • 其它
    • 其它
      • Form Builder
      • Renderer
      • Basic Implicit Render
      • Railties Helpers
  • Active Support 扩展:autoload 的类和模块
    • Autoload
      • autoload & eager_autoload 补充
    • Lazy Load Hooks
    • Concern
    • File Update Checker
    • Notifications
      • Rails 默认已有的 instrumenter
    • Subscriber
    • Log Subscriber
      • Action Mailer Log Subscriber
      • Action Controller Log Subscriber
      • Action View Log Subscriber
      • Active Record Log Subscriber
    • Rescuable
    • Descendants Tracker
    • Dependencies
  • Active Support 扩展:eager_autoload 的类和模块
    • Cache 缓存的源头
    • Callback 方法解释及使用
    • Callbacks 底层简要分析
    • Configurable
    • Ordered Hash 和 Ordered Options
    • Inflector
    • Key Generator 和 Caching Key Generator
    • Message Encryptor 和 Message Verifier
    • String Inquirer - Rails.env.production?
    • Array Inquirer
    • Tagged Logging
    • Gzip 与 JSON
    • Backtrace Cleaner
    • Number Helper
    • Benchmarkable
    • Xml Mini
    • Multibyte
    • Deprecation
    • 其它
  • Active Support 核心扩展
    • Array
    • Benchmark
    • Big Decimal
    • Class
    • Date
    • Time
    • Date Time
    • Duration
    • Time With Zone
    • Time Zone
    • Enumerable
    • File
    • Hash
    • Hash With Indifferent Access
    • Integer
    • Numeric
    • Kernel
    • Object
    • Module
      • alias_method_chain
    • Marshal
    • Range
    • Regexp
    • Secure Random
    • String
    • URI
    • Load Error
    • Name Error
    • Logger
    • Logger Silence
  • Active Support 其它类和模块
    • Security Utils
  • railties 核心:初始化、组件化
    • Railtie
      • Railtie 文件下的内容
      • Initializable
      • Configuration
      • 定制自己的 Railtie
    • Railtie 补充
      • Rails 默认组件都是 Railtie
    • Engine
      • Engine 文件下的内容
      • Configuration
      • Engine full vs mountable
      • 定制自己的 Engine
      • 其它
    • Application
      • Application 文件下的内容
      • Bootstrap
      • Finisher
      • Configuration
      • Default Middleware Stack
      • Rails 应用启动过程
    • Application 补充
      • Routes Reloader
      • rake & rails 命令
      • rails console 里的小技巧
      • 路径 - Root 和 Path
      • 提示信息页面
    • 其它
      • Rails 文件下的内容
      • Configuration Middleware Stack Proxy
      • AppName, Application. Engine, Railtie
      • Backtrace Cleaner
      • Rack Logger
      • Generators
  • Rails Configuration 配置
    • 一般常用配置项
    • Action Mailer
    • Active Record
    • Action Controller
    • Action Dispatch
    • Action View
    • Active Support
    • I18n
    • Generators
    • Assets
    • Environments
    • 设置项补充
    • Middleware
  • Rails Generators 代码生成器
    • Thor
    • generators 下的目录、文件
    • Base
    • Actions
    • Named Base
    • 其它
      • App Base
      • Generators 文件下的内容
      • Migration
      • Active Model
      • Resource Helpers
      • Model Helpers
      • Generated Attribute
  • Action Mailer 发邮件
    • Base
      • 拦截器 register_interceptor
      • 订阅者 register_observer
    • Mail Helper
    • Message Delivery
    • 其它
      • Delivery Methods
      • Previews & Preview
      • DeliveryJob
      • Collector
  • Active Job 异步任务
    • Active Job 使用
    • Active Job 补充
  • Action Cable 封装的 WebSockets
    • 服务端 - Ruby 代码
      • Channel
      • Channel 补充
      • Connection
      • Connection 补充
      • Server
      • Server 补充
      • Remote Connections
      • Action Cable Helper
      • Subscription Adapter
      • Subscription Adapter 补充
    • 客户端 - Coffee 脚本
      • Action Cable 文件下的内容
      • Consumer
      • Subscription
      • Connection
      • Subscriptions
      • Connection Monitor
    • 一些重要的东西
    • 其它
  • Active Storage 存储功能最小实现
  • 前端 Turbolinks
  • 前端 Webpacker
  • 测试 Testing
    • Active Support
    • Active Job
    • Action Mailer
    • Action Controller
    • Action Dispatch
    • Action View
    • Generators
    • rails-dom-testing
  • 测试 MiniTest
    • Spec DSL
    • Assertions
    • Mock
    • Unit
      • TestCase
      • Lifecycle Hooks
      • Guard
    • Expectations
    • 其它
  • 测试 Factory Girl
  • rails-guides 指南
  • 其它
    • 继承心得
    • Rails 源代码里一些常用方法
    • Rails assets precompile
    • Turbolinks 产生的原因
    • Turbolinks 3
    • Turbolinks 补充
    • Turbolinks 5
  • 后记
由 GitBook 提供支持
在本页
  • 一,创建自己的 Engine
  • 二,编写 my_engine/engine.rb 文件内容
  • 三,编写 Engine 内容
  • 四,在 main_app 引入定制的 Engine

这有帮助吗?

  1. railties 核心:初始化、组件化
  2. Engine

定制自己的 Engine

Engine = Ruby gem + Rails MVC stack elements.

一,创建自己的 Engine

可用命令 rails plugin new 创建自己的 Engine. 常用可选参数 --full 或 --mountable

两者之间的区别,可以参考【Engine full vs mountable】章节。

拆分一下,步骤大概如下:

1) 继承于 Rails::Engine,一般把它们放在 lib/ 目录下。

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

2) 在 config/application.rb (或 Gemfile) 里加载本文件。

Engine 相关的 model、controller 和 helper 会被加载到 app/ 里,route 会被加载到 config/routes.rb, locale 会被加载到 config/locales, tasks 会被加载到 lib/tasks.

# config/application.rb
require 'my_engine/engine'

# 或者

# Gemfile
gem 'my_engine', path: "/path/to/my_engine"

3) 在 routes.rb 里 mount MyEngine::Engine

Rails.application.routes.draw do
  mount MyEngine::Engine => "/engine"
end

二,编写 my_engine/engine.rb 文件内容

每个 Engine 都会有自己的 engine.rb 文件。里面有自己的 Engine 类,它继承于 ::Rails::Engine

1) 常用方法之 config、initializer

在这文件里,你可以使用 config, initializer 等方法。这点和定制 Railtie 类似,但不同点是:当前 Engine 的配置和初始化,作用域仅限于当前 Engine.

class MyEngine < Rails::Engine
  # 添加新的、额外的目录到 autoload_paths 里
  config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)

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

config 是个方法,但同时它也是 Configuration 的实例对象,所以你可以使用 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

2) 常用方法之 isolate_namespace

默认 Engine 和应用是在一个环境里的,这意味着应用所有 helper 和命名路由都可以在 Engine 里使用。

你可以使用 isolate_namespace 更改此项默认配置,将 Engine 和应用隔离出来。使用举例:

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

此时 MyEngine 和应用是隔离了的,假设 MyEngine 有代码:

module MyEngine
  class FooController < ActionController::Base
  end
end

此时 FooController 仅能使用 Engine 里提供的 helper,以及 MyEngine::Engine.routes 提供的 url helper.

另外一个改变就是 Engine 里的路由不必再使用 namespace,举例:

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

resources :articles 自动对应着 MyEngine::ArticlesController. 并且不必使用长长的 url helper,例如 my_engine_articles_path 可以直接使用 articles_path

不受 isolate_namespace 影响的就是对于 model 的调用,仍然使用 engine_name 做为前缀。例如以下例子的 MyEngine::Article

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

另一个改变是对表名的更改。默认使用 engine_name (在这里是 "my_engine")做为表前缀,也就是说 MyEngine::Article 对应的表名应该是 my_engine_articles

3) 常用方法之 paths

Engine 默认都有自己的文件、目录结构,如果你没有定制,那么就使用默认的:

"app",                 eager_load: true, glob: "*"
"app/assets",          glob: "*"
"app/controllers",     eager_load: true
"app/helpers",         eager_load: true
"app/models",          eager_load: true
"app/mailers",         eager_load: true
"app/views"

"app/controllers/concerns", eager_load: true
"app/models/concerns",      eager_load: true

"lib",                 load_path: true
"lib/assets",          glob: "*"
"lib/tasks",           glob: "**/*.rake"

"config"
"config/environments", glob: "#{Rails.env}.rb"
"config/initializers", glob: "**/*.rb"
"config/locales",      glob: "*.{rb,yml}"
"config/routes.rb"

"db"
"db/migrate"
"db/seeds.rb"

"vendor",              load_path: true
"vendor/assets",       glob: "*"

paths 通过它,可以更改默认的文件、目录结构。

举例,你想把 controller 文件放到 lib/ 目录下:

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

再或者,controller 在 app/ 和 lib/ 下都可接受:

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

Application 在 Engine 之上,它又有自己的配置和初始化。它配置了 app/ 下的文件、目录会被自动加载,所以像 app/services 会被自动加载。

4) 常用方法之 endpoint

Engine 内容也可以是一个 Rack Application. 当你的代码本身是 Rack Application,而又想使用 Engine 的特性时,可以这么做:

1) 在自己定义的 Engine 里,使用 endpoint:

module MyEngine
  class Engine < Rails::Engine
    # Engine 的内容就是 MyRackApplication
    endpoint MyRackApplication
  end
end

2) 和平常一样,在 route 里 mount 你的 Engine:

Rails.application.routes.draw do
  mount MyEngine::Engine => "/engine"
end

5) 常用方法之 middleware

Engine 内容也可以是一个 Middleware. 当你的代码本身是 Middleware,而又想使用 Engine 的特性时,可以这么做:

module MyEngine
  class Engine < Rails::Engine
    # Engine 的内容就是 SomeMiddleware
    middleware.use SomeMiddleware
  end
end

6) 常用方法之 engine_name

用几个场景可能会用到 engine name:

  • routes: 当你使用 mount(MyEngine::Engine => '/my_engine')

  • rake task: 当你使用 my_engine:install:migrations

Engine name 默认根据类名而来,如 MyEngine::Engine 对应有 my_engine_engine. 你可以使用 engine_name 进行自定义:

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

三,编写 Engine 内容

做了上述两步后,就是编写内容。该做什么事,做什么事;该完成什么功能,完成什么功能。

四,在 main_app 引入定制的 Engine

也就是:

在 config/application.rb (或 Gemfile) 里加载本文件。 在 routes.rb 里 mount MyEngine::Engine

上一页Engine full vs mountable下一页其它

最后更新于5年前

这有帮助吗?