コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

ActiveModel::Attributesはプレーンな値を持つだけのオブジェクトを作るときに値をよしなに処理してくれるので便利

型が欲しい!!!とか思ったときそっと添えることのできる機能として

環境

$ bin/rails -v
Rails 5.2.2

class NoRecordUser
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :age, :integer
  attribute :height, :float
  attribute :weight, :float
end

こんな感じでClassを作ると

user = NoRecordUser.new(name: "taro")
user.name
#=> "taro"

という感じで取れる。 また、型的におかしいものをいれると…

user.age = "ziro"
p user.age
0

という感じで丸めてくれる。

参考リンク