Module: ActivemodelObjectInfo::TableDefinition
- Defined in:
- lib/activemodel_object_info/table_definition.rb
Overview
重新扩展一些方法,用来方便在创建迁移文件的时候进行一些通用类的设定。 从 @version 0.3.0 开始支持了自动创建的时间戳字段增加索引
核心作用与职责: 在 ActiveRecord 数据库迁移(Migration)建表时,提供便捷的宏方法, 一键生成通用的审计追踪字段(如操作人、操作时间)及软删除字段。
核心重要方法:
- #operation_columns:生成指定操作的审计字段(含前缀、后缀配置)。
- #generate_operations:批量生成创建、更新、删除相关的全套审计字段。
[Changelog] [2026-07-28] 补充完整 YARD 文档、行内注释,清理尾随空格 (shiner527) [2021-04-20] 支持自动创建的时间戳字段增加索引 (@version 0.3.0) (shiner527) [2021-04-19] 创建基础模块,提供 operation_columns 与 generate_operations (shiner527)
Instance Method Summary collapse
-
#generate_operations(*operations) ⇒ Object
生成对应操作的字段,包括操作人和操作时间戳,均使用默认设置。.
-
#operation_columns(*fields, **options) ⇒ Object
生成操作相关的字段。包含操作人、操作时间等信息。.
Instance Method Details
#generate_operations(*operations) ⇒ Object
生成对应操作的字段,包括操作人和操作时间戳,均使用默认设置。
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/activemodel_object_info/table_definition.rb', line 102 def generate_operations(*operations) # puts "generate_operations(#{operations})" action_fields = operations # 1. 如果没有给出具体的动作名称,默认配置为创建、更新和删除这三个常规生命周期动作 action_fields = %w[created updated deleted] if action_fields.empty? # 2. 遍历所有的动作名称以生成相应的字段 action_fields.each do |operation| # 3. 特殊逻辑:当遇到 deleted 动作时,除了生成审计字段外,还需要额外部署一个整型的标记字段,用于承载软删除状态 column(operation.to_s, :integer, default: 0, comment: '删除标记') if operation.to_sym == :deleted # 4. 复用 operation_columns 方法来生成对应的 xxx_by 操作人和 xxx_at 操作时间字段 operation_columns(operation) end end |
#operation_columns(*fields, **options) ⇒ Object
生成操作相关的字段。包含操作人、操作时间等信息。
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/activemodel_object_info/table_definition.rb', line 69 def operation_columns(*fields, **) # puts "operation_columns(#{fields}, #{options})" # 1. 提取并初始化各种设置选项,对于布尔值优先取用户配置,未配置则默认为 true with_operator = [:with_operator].nil? ? true : [:with_operator] = [:with_timestamp].nil? ? true : [:with_timestamp] operator_prefix = [:operator_prefix] operator_suffix = [:operator_suffix] || '_by' = [:timestamp_prefix] = [:timestamp_suffix] || '_at' # 2. 遍历每一个需要生成的操作标识符 fields.each do |field| # 3. 动态拼接并生成操作人记录字段 (默认为 bigint 类型并添加索引) if with_operator operator_column_name = operator_prefix.to_s + field.to_s + operator_suffix.to_s column(operator_column_name, :bigint, index: true, comment: '操作人') if operator_column_name.present? end # 4. 动态拼接并生成操作时间戳字段 (默认为 datetime 类型并添加索引) if = .to_s + field.to_s + .to_s column(, :datetime, index: true, comment: '操作时间戳') if .present? end end end |