如何注册支持参数配置的ActiveModel属性类型?
可以实现,具体步骤如下
首先,确保自定义类型类支持初始化参数:
module Types class VirtualStringType < ActiveModel::Type::String def initialize(suffix: nil) super() @suffix = suffix end # 根据业务需求重写类型方法,比如给值添加后缀 def cast(value) return super unless @suffix.present? "#{super}#{@suffix}" end end end
然后注册该类型到ActiveModel的类型映射中:
ActiveModel::Type.register(:virtual_string, Types::VirtualStringType)
完成注册后,就能在模型里按照你想要的方式使用了:
class Action < ApplicationRecord attribute :type, :virtual_string, suffix: 'Action' end
原理说明
当你用符号:virtual_string指定属性类型时,Rails会通过注册的映射找到对应的Types::VirtualStringType类,并将attribute方法中传入的额外参数(如suffix: 'Action')传递给该类的initialize方法,自动完成实例化。
如果需要更复杂的参数处理逻辑,也可以在注册时自定义构造过程:
ActiveModel::Type.register(:virtual_string) do |suffix: nil| Types::VirtualStringType.new(suffix: suffix) end
内容的提问来源于stack exchange,提问作者Ostap Brehin
相关产品推荐
相关产品推荐

