Active Model Attributes
Attributes
模組允許模型定義超越 Ruby 純粹讀寫的屬性。類似於通常從資料庫結構推論的「Active Record」屬性,Active Model
Attributes
意識到資料類型,可以有預設值,並可以處理轉型和序列化。
要使用 Attributes
,請在模型類別中包含模組,並使用 attribute
巨集定義屬性。它接受名稱、類型、預設值和屬性類型支援的任何其他選項。
範例
class Person
include ActiveModel::Attributes
attribute :name, :string
attribute :active, :boolean, default: true
end
person = Person.new
person.name = "Volmer"
person.name # => "Volmer"
person.active # => true
命名空間
方法
包含的模組
執行個體公共方法
attribute_names() 連結
傳回屬性名稱陣列為字串。
class Person
include ActiveModel::Attributes
attribute :name, :string
attribute :age, :integer
end
person = Person.new
person.attribute_names # => ["name", "age"]
來源: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 146 def attribute_names @attributes.keys end
attributes() 連結
傳回所有屬性的雜湊,屬性名稱為鍵,屬性值為值。
class Person
include ActiveModel::Attributes
attribute :name, :string
attribute :age, :integer
end
person = Person.new
person.name = "Francesco"
person.age = 22
person.attributes # => { "name" => "Francesco", "age" => 22}
來源: 顯示 | 於 GitHub 上
# File activemodel/lib/active_model/attributes.rb, line 131 def attributes @attributes.to_hash end