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"
方法