在 dry-types 与 RBS 之间做双向类型同步
解读
国内 Rails 团队近年出现“渐进式类型落地”的分层策略:
- 对外 API 与关键模型用 RBS 做静态声明,方便 Sorbet/Steep 做 CI 检查;
- 内部业务逻辑用 dry-types 做运行时契约,兼顾灵活与防御式编程。
面试题要求“双向同步”,本质考察候选人能否把运行时类型信息(dry-types Schema)无损地翻译成静态类型签名(RBS),同时把 RBS 的改动反向同步回 dry-types,保证单一真相源,避免“两层皮”导致类型漂移。
现场常追问:
- 同步粒度是字段级还是模块级?
- 遇到 dry-types 的 sum-type、optional、constrained 如何映射到 RBS 的 union、nilable、interface?
- 如何嵌入现有 CI,让 PR 阶段就阻断不同步?
答不出自动化方案,会直接被判定“只能手工对表”,面试分大打折扣。
知识点
- dry-types 内部 DSL 解析:
Types::Hash.schema返回的 AST 节点可递归遍历;type.options里存着:member、:default、:constructor等元数据。
- RBS 语法子集:
- 顶层
class/module声明、attr_reader、def方法类型; untyped、nil、bool、Integer、String、Array[T]、Hash[K, V]、T | U、_Interface;- 泛型参数与边界
type param声明。
- 顶层
- 双向同步核心算法:
- 正向(dry-types → RBS):深度优先遍历 schema,维护字段名→RBS 类型的映射表;遇到
Types::Strict::Integer、Types::Params::Date等映射到Integer、::Date;遇到Types::Nominal::Any退化为untyped;遇到constrained(type: String, size: 1..10)生成自定义接口interface _StringSize1To10并在 RBS 里引用。 - 反向(RBS → dry-types):用
rbsgem 的RBS::Parser.parse_signature生成 AST,再按字段类型反向拼出Dry::Types['strict.int']、Types::String.constrained(size: 1..10)等;对union类型优先拆成Types::String | Types::Nil以保留 optional 语义。
- 正向(dry-types → RBS):深度优先遍历 schema,维护字段名→RBS 类型的映射表;遇到
- 冲突消解策略:
- 以 git 时间戳为基准,后改者胜出;
- 对“手动编辑过的 RBS” 加
# @manual注释,同步脚本跳过,防止覆盖。
- 工程化落地:
- 封装为
rake types:sync:export与rake types:sync:import; - 在 GitHub Actions 里跑
steep check && rake types:sync:diff,若 diff 非空则 CI 失败,强制开发者先同步再合并; - 提供
--dry-run与--interactive模式,符合国内“code review 必须可灰度”的合规要求。
- 封装为
答案
下面给出一套可直接落地的 Ruby 脚本骨架,演示最小双向同步闭环。
核心思路:
- 把 dry-types Schema 当成“运行时 AST”,用
Dry::Types::Schema#keys递归提取类型; - 用
rbsgem 把 RBS 文件解析成 Ruby 对象,再反向生成 dry-types 调用; - 全部封装成两个 Rake 任务,CI 可调用。
# lib/types_sync.rb
module TypesSync
# 正向:dry-types -> RBS
def self.export_to_rbs(const_name, schema_klass)
rbs_lines = ["class #{const_name}"]
schema_klass.schema.each do |key, type|
rbs_type = to_rbs_type(type)
rbs_lines << " attr_reader #{key}: #{rbs_type}"
end
rbs_lines << "end"
Pathname("sig/#{const_name.underscore}.rbs").write(rbs_lines.join("\n"))
end
def self.to_rbs_type(type)
case type
when Dry::Types::Constrained
# 生成接口避免爆炸
"::_StringConstrained" # 简化示例,真实可拼 size 范围
when Dry::Types::Sum
left, right = type.left, type.right
if right.primitive == NilClass
"#{to_rbs_type(left)}?"
else
"#{to_rbs_type(left)} | #{to_rbs_type(right)}"
end
else
MAP[type.primitive] || 'untyped'
end
end
MAP = { String => '::String', Integer => '::Integer', NilClass => 'nil' }.freeze
# 反向:RBS -> dry-types
def self.import_from_rbs(rbs_path)
sig = RBS::Parser.parse_signature(rbs_path.read)
sig.declarations.each do |decl|
next unless decl.is_a?(RBS::AST::Declarations::Class)
klass_name = decl.name.name
schema = {}
decl.members.each do |member|
next unless member.is_a?(RBS::AST::Members::AttrReader)
schema[member.name] = to_dry_type(member.type)
end
# 动态定义 dry-struct
StructKlass = Class.new(Dry::Struct) do
schema.each { |k, v| attribute k, v }
end
Object.const_set(klass_name, StructKlass)
end
end
def self.to_dry_type(rbs_type)
case rbs_type
when RBS::Types::Optional
to_dry_type(rbs_type.type).optional
when RBS::Types::Union
Types::String | Types::Nil # 简化,真实需递归
when RBS::Types::ClassInstance
name = rbs_type.name.name
"Types::Strict::#{name}".constantize
else
Types::Any
end
end
end
# Rakefile
namespace :types do
namespace :sync do
desc 'Export dry-types schema to RBS'
task export: :environment do
TypesSync.export_to_rbs('User', UserStruct)
end
desc 'Import RBS to dry-types'
task import: :environment do
TypesSync.import_from_rbs('sig/user.rbs')
end
desc 'Check if RBS diff exists'
task diff: :environment do
sh 'git diff --exit-code sig/*.rbs' do |ok, _|
abort '❌ RBS 与 dry-types 不同步,请先执行 rake types:sync:export' unless ok
end
end
end
end
落地步骤:
- 把上述文件放入工程,
bundle add rbs dry-types; - 在 CI 里加两步:
bundle exec rake types:sync:exportbundle exec rake types:sync:diff
若 diff 非零直接失败;
- 代码审查时,只允许
*.rbs与*_schema.rb同时变更,否则 review 不通过。
如此即可在不增加团队心智负担的前提下,实现 dry-types 与 RBS 的自动化双向同步,满足国内“静态检查+运行时契约”双轨并行的主流落地模式。
拓展思考
- 性能与体积:当 schema 达到上千字段时,全量导出 RBS 文件会膨胀。可引入增量哈希缓存:把 schema 的
object_id+type.hash写进.types-sync-cache,只有变更的常量才重写 RBS,CI 耗时从 30s 降到 3s。 - 泛型与 higher-kinded 类型:dry-types 支持
Types::Array.of(Types::Hash.schema(...)),RBS 侧需生成Array[{ x: Integer }]。此时要把to_rbs_type改成递归下降,对Types::Array.member解析出T再拼Array[T],否则 Steep 会报“无法匹配泛型实参”。 - 与 Sorbet 并存:国内部分大厂已在用 Sorbet。可再写一条通道把 RBS 转成 RBI,实现 dry-types → RBS → RBI 的三级联动,一套 schema 同时喂给 Steep 与 Sorbet,避免重复写 sig。
- 运行时回写:在 Rails 开发环境启动时,自动检测
db/schema.rb变更,触发rake types:sync:export,实现“迁移即类型”,把数据库约束同步到 dry-types 再同步到 RBS,打通 DB ↔ Ruby ↔ Static 的完整闭环。