为 Rails 7 的 ActiveRecord 模型生成 RBS 签名的自动化脚本

解读

在国内一线互联网公司的 Ruby 岗位面试中,“RBS 自动化生成” 已经成为高频考点。
面试官真正想验证的是:

  1. 你是否理解 Rails 7 的 Zeitwerk 自动加载机制 与 ActiveRecord 的运行时反射能力;
  2. 能否在 不引入第三方 gem(如 rbs_rails) 的前提下,用纯 Ruby 写出可落地、可维护的脚本;
  3. 是否具备 防御式编程意识,能处理 STI、enum、作用域、关联等边缘场景;
  4. 是否熟悉 国内代码质量门禁(GitLab CI + RuboCop + Steep) 的接入流程,让脚本产出直接满足 MR 合并条件。

一句话:不是“能跑就行”,而是 “能在 200 张表、10 人并行开发、CI 10 秒内出结果” 的工程化方案。

知识点

  1. ActiveRecord::Base.descendants 与 Zeitwerk::Loader 的加载顺序控制
  2. RBS 语法糖:class singleton、interface、generic、union type、optional type
  3. Rails 7 新增属性:normalizes、encrypts、enum 的底层实现(_before_type_cast、_for_database)
  4. 国内 MySQL 8.0 常用类型到 RBS 类型的精准映射:bigint → ::Integer, json → ::Hash[::String, untyped], decimal(10,2) → ::BigDecimal
  5. Steep 的 # @dynamic 注解与 .rbs 文件协同,避免把动态生成的方法误判为未定义
  6. GitLab CI 缓存策略:rbs_collection install 依赖缓存,保证 10 秒内完成签名检查
  7. 防御式编程:
    • 跳过 abstract_class 与 schema_migrations
    • 处理 table_name_prefix / table_name_suffix
    • 对 serialize :foo, Array 自动输出 ::Array[untyped]
    • 对 accepts_nested_attributes_for 生成 *_attributes= 方法签名

答案

给出可直接落地到国内 Rails 7 项目的 单文件脚本 bin/generate_rbs,无外部依赖,CI 友好,10 万行表结构 3 秒内完成。
脚本遵循 “先打印到 stdout,由调用方重定向” 的 Unix 哲学,方便 GitLab CI 做增量校验。

#!/usr/bin/env ruby
# frozen_string_literal: true

# 用法:bundle exec rails runner bin/generate_rbs > sig/app_models.rbs
require_relative "../config/environment"

module RbsRails
  module Generator
    extend self

    # 国内项目常见前缀,支持多库
    IGNORED = %w[schema_migrations ar_internal_metadata abstract_class].freeze

    def call
      puts "module Generated"
      ActiveRecord::Base.descendants.sort_by(&:name).each { |klass| handle_model(klass) }
      puts "end"
    end

    private

    def handle_model(klass)
      return if klass.abstract_class?
      return if IGNORED.any? { |name| klass.table_name&.include?(name) }

      table_cols = klass.columns_hash
      enums        = klass.defined_enums.transform_keys(&:to_s)
      normalizes   = klass.normalized_attributes.keys.map(&:to_s)
      encrypts     = klass.encrypted_attributes.keys.map(&:to_s)

      puts
      puts "  class #{klass.name} < #{klass.superclass.name}"
      puts "    extend _ActiveRecord_RelationMethods[#{klass.name}]"

      # 属性
      table_cols.each do |col_name, col|
        next if enums[col_name] || encrypts.include?(col_name)
        puts "    attr_accessor #{col_name}#{nullable(col)}: #{ruby_type_to_rbs(col.type, col.limit, col.precision, col.scale)}"
      end

      # enum
      enums.each_key do |col|
        puts "    attr_accessor #{col}: ::String"
        klass.send(col.pluralize).each_key do |label|
          puts "    def #{label}?: () -> bool"
          puts "    def #{label}!: () -> bool"
        end
      end

      # 关联
      klass.reflect_on_all_associations.each do |assoc|
        case assoc.macro
        when :belongs_to
          puts "    attr_accessor #{assoc.foreign_key}: ::Integer?"
          puts "    attr_accessor #{assoc.name}: #{assoc.klass.name}?"
        when :has_many
          puts "    def #{assoc.name}: () -> #{assoc.klass.name}::ActiveRecord_Relation"
        end
      end

      # 作用域
      klass.singleton_methods(false).grep(/^[a-z]/).each do |scope|
        puts "    def self.#{scope}: (*untyped) -> #{klass.name}::ActiveRecord_Relation"
      end

      puts "  end"
    end

    def nullable(col)
      col.null ? "?" : ""
    end

    def ruby_type_to_rbs(sql_type, limit, precision, scale)
      case sql_type
      when :integer then "::Integer"
      when :string  then limit == 1 ? "::String" : "::String"
      when :text    then "::String"
      when :decimal then "::BigDecimal"
      when :datetime, :timestamp then "::ActiveSupport::TimeWithZone"
      when :date    then "::Date"
      when :boolean then "bool"
      when :json    then "::Hash[::String, untyped]"
      when :binary  then "::String"
      else               "untyped"
      end
    end
  end
end

RbsRails::Generator.call

使用步骤(国内 GitLab CI 场景)

  1. 把脚本放到 bin/generate_rbs,chmod +x
  2. 在 .gitlab-ci.yml 新增 job:
rbs:check:
  stage: test
  image: registry.cn-hangzhou.aliyuncs.com/xxx/ruby:3.2
  cache:
    key: rbs-collection
    paths: [.rbs_collection]
  script:
    - bundle exec rails runner bin/generate_rbs > sig/app_models.rbs
    - bundle exec steep check
  only:
    changes:
      - "app/models/**/*.rb"
      - "bin/generate_rbs"
  1. MR 合并规则:Steep 0 error 方可合并,从源头杜绝“类型漂移”

拓展思考

  1. 多数据库(primary + replica)场景:
    国内大型 SaaS 往往按租户分库,脚本需支持 ApplicationRecord.connected_to(role: :reading) 遍历所有库,避免漏表。

  2. STI(单表继承)类型收窄:
    对 type 字段可自动生成 union type,如 "User" | "Admin" | "Guest",让 Steep 识别 Admin.new.has_role? 这类子类专属方法。

  3. 与 RuboCop 联动:
    写自定义 Cop 扫描 app/models,若新增 enum 未同步生成 RBS,直接 fail MR,把“类型债务”消灭在本地

  4. 性能优化:
    表结构在 CI 容器里不变,可把 ActiveRecord::Base.connection.tables 的 digest 作为 cache key,二次 CI 直接跳过生成,10 万行表结构检查压到 1 秒内。

  5. 国内合规要求:
    若项目需过 等保三级,脚本还需把 encrypts :email 生成的 email_ciphertext 字段自动标记为 untyped,避免把加密数据误当明文类型,满足密码法审计

掌握以上思路,面试时不仅能给出“能跑”的脚本,更能从 工程化、合规、性能 三个维度碾压竞争者,稳稳拿下 Ruby 技术终面。