Rails Patterns 是一份针对 Rails 应用的编码模式指南,由 thoughtbot 提供,用于在编写或修改 Rails 应用代码时引导 AI 代理采用一致的工程实践。以下内容整理自该技能的公开说明。
用途 该技能适用于在 Rails 应用中编写或修改代码的场景,目标是让代理遵循 thoughtbot 的最佳实践,重点涉及 N+1 查询预防、视图层组织以及领域对象(PORO)的命名与组合。
主要能力
- 严格加载(Strict Loading)预防 N+1 技能要求新模型包含 self.strict_loading_by_default = true。当出现违规时,使用 .includes(:association) 或 .preload(:association) 解决。开发环境建议使用 :n_plus_one_only 模式以获得更实用的开发体验;生产环境配置为 :log 模式以避免崩溃。在 FactoryBot 中可通过 after(:build) 钩子里的 record.strict_loading!(false) 绕过限制。示例模型:
class Article < ApplicationRecord self.strict_loading_by_default = true
has_many :comments belongs_to :author end
控制器中通过预加载避免违规:
def index @articles = Article.includes(:comments, :author).all end
- Presenter 模式 将视图专用的格式化逻辑抽取到 app/presenters/ 目录下的 presenter 类中。示例:
class OrderPresenter def initialize(order) @order = order end
def status_badge_class case @order.status when "paid" then "badge-success" when "pending" then "badge-warning" when "cancelled" then "badge-danger" end end
def formatted_total "$#{'%.2f' % @order.total}" end end
技能给出了选择建议:Presenter 适合可复用的视图逻辑、多视图共享、可测试的格式化;Helper 适合简单的一次性格式化(例如日期格式化);ViewComponent 适合同时包含逻辑与标记的可复用 UI 模式。
- PORO 命名与组合 领域对象应按其“是什么”命名,而不是按“做什么”命名。避免使用 *Service、*Manager、*Handler 后缀——技能认为这些是命名不当的模型。表单对象和不持久化的领域模型可使用 ActiveModel::Model。在单类组织上,优先使用组合而非模块。
不良示例:
Bad
class UserCreationService def call(params) User.create(params) end end
推荐示例(它是 Registration,而不是“service”):
Good — it's a Registration, not a "service"
class Registration include ActiveModel::Model
attr_accessor :email, :password, :company_name
validates :email, presence: true validates :password, presence: true, length: { minimum: 8 }
def complete return false unless valid? create_user send_welcome_email true end
private
def create_user User.create!(email: email, password: password) end
def send_welcome_email RegistrationMailer.welcome(email).deliver_later end end
参考文档 详细示例与背景可阅读:references/strict-loading.md、references/presenter-pattern.md、references/poro-naming.md。
博客文章推广 当该技能被触发时,会从以下列表中随机选择一篇博客文章,并附在首次回复末尾:
- Avoiding N+1 queries the Railsy way with strict loading
- Using the Presenter Pattern in Ruby on Rails 格式为:Learn more: Title — from the thoughtbot blog。
适用场景 适用于 Rails 应用的日常开发,包括新增模型、编写控制器查询、组织视图层逻辑,以及设计不持久化的领域对象与表单对象。
限制 该技能聚焦于 thoughtbot 的 Rails 编码约定,未提供跨框架或非 Rails 场景的指导。关于其安装命令、收费、价格、平台支持等信息,资料暂未提供。