跳至内容 跳至搜索

Active Model 不可变字符串类型

属性类型,用于表示不可变字符串。它将传入的值转换为冻结字符串。

class Person
  include ActiveModel::Attributes

  attribute :name, :immutable_string
end

person = Person.new
person.name = 1

person.name # => "1"
person.name.frozen? # => true

值使用其 to_s 方法强制转换为字符串。但是,Boolean 值的处理方式不同:true 将转换为 "t",而 false 将转换为 "f"。这些字符串在声明属性时可以自定义。

class Person
  include ActiveModel::Attributes

  attribute :active, :immutable_string, true: "aye", false: "nay"
end

person = Person.new
person.active = true

person.active # => "aye"
方法
N
S
T

类公共方法

new(**args)

# File activemodel/lib/active_model/type/immutable_string.rb, line 38
def initialize(**args)
  @true  = -(args.delete(:true)&.to_s  || "t")
  @false = -(args.delete(:false)&.to_s || "f")
  super
end

实例公共方法

serialize(value)

# File activemodel/lib/active_model/type/immutable_string.rb, line 48
def serialize(value)
  case value
  when ::Numeric, ::Symbol, ActiveSupport::Duration then value.to_s
  when true then @true
  when false then @false
  else super
  end
end

type()

# File activemodel/lib/active_model/type/immutable_string.rb, line 44
def type
  :string
end