跳至內容 跳至搜尋

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