Active Model ImmutableString 类型¶ ↑
表示不可变字符串的属性类型。它会将传入的值强制转换为冻结的字符串。
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"
方法
包含的模块
类公共方法
new(**args) 链接
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/type/immutable_string.rb, line 40 def initialize(**args) @true = -(args.delete(:true)&.to_s || "t") @false = -(args.delete(:false)&.to_s || "f") super end
实例公共方法
serialize(value) 链接
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/type/immutable_string.rb, line 50 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() 链接
来源: 显示 | 在 GitHub 上
# File activemodel/lib/active_model/type/immutable_string.rb, line 46 def type :string end