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 提供支持
在本页
  • mount as - 在 Engine 之外使用其路由
  • helper - Isolated engine's helpers
  • Migrations & seed data
  • 改变加载顺序,优先加载
  • 迁移文件
  • 提示

这有帮助吗?

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

其它

mount as - 在 Engine 之外使用其路由

mount(挂载)后 Engine 和应用之间的路由仍然是独立的,你仍然不能在应用里直接使用 Engine 里面的路由。举例:

# config/routes.rb
Rails.application.routes.draw do
  mount MyEngine::Engine => "/my_engine", as: "my_engine"
  get "/foo" => "foo#index"
end

Engine 外面,使用 my_engine 访问 Engine 里面的路由:

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

Engine 里面,使用 main_app 访问 Engine 外面的路由:

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

:as 可选项默认使用的是 engine_name,所以通常你可以省略它。

还有一种情况,需要传递 engine_name 以便生成路由,举例:

form_for([my_engine, @user])

这里生成的路由规则类似 my_engine.user_path(@user)

helper - Isolated engine's helpers

有时候,你的 Engine 是 Isolated,但你又想使用 Engine 里面定义的 helper,你可以引入某个模块:

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

或者,引入 Engine 里面所有的 helper 模块:

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

Note: 这里引入的只是 helpers 目录下的文件,在 Controller 里定义,然后使用 helper_method 的方法不包含在内。

Migrations & seed data

Engine 也可以有自己的迁移文件,和普通应用一样,它们位于 db/migrate 下面。

你可以运行以下命令,将 Engine 里的迁移文件复制到应用里:

rake ENGINE_NAME:install:migrations

Engine 也可以有自己的 seed 文件,它们位于 db/seeds.rb 下面。

你可以运行以下命令,将 Engine 里的 seed 文件复制到应用里:

MyEngine::Engine.load_seed

改变加载顺序,优先加载

场景

- app
  - views
    - shared
      - _header.html.erb       <-- 实际渲染的却是这个
  - ...
- config
- ...
- vendors
  - plugins
    - myplugin
      - app
        - views
          - controller1
            - action1.html.erb <-- 在这里渲染
          - shared
            - _header.html.erb <-- 希望渲染的是这个

<%= render 'shared/header' %>

按照直观的理解,渲染的应该是第 2 个模板。但实际情况却不是,所以需要我们配置。

你可以使用 config.railties_order 改变 Engine 以及应用的加载顺序:

# load Blog::Engine with highest priority, followed by application and other railties
config.railties_order = [Blog::Engine, :main_app, :all]

main_app 表示我们的项目本身,在 Application::Finisher 里定义,all 表示所有其它的 Railtie,在 Application::Configuration 里初始化时定义。

Note: 上面的例子,你也可以用其它手段完成,如 namespace 等。

迁移文件

rake my_engine:install:migrations

提示

除了 initializer 外,rake_tasks 也会被复制到 main_app 里。所以,有时候你会看到提示: "Copy migrations from #{railtie_name} to application"

上一页定制自己的 Engine下一页Application

最后更新于5年前

这有帮助吗?