ブシトラの日記

エンジニア1年生の雑多記事

Railsガイド6.0読み直す ~7章 Active Model の基礎

railsguides.jp

 

PostgreSQL と 複数のデータベース利用はスキップ

1 AttributeMethodsモジュール

class Person
  include ActiveModel::AttributeMethods

  attribute_method_prefix 'reset_'
  attribute_method_suffix '_highest?'
  define_attribute_methods 'age'

  attr_accessor :age

    private
    def reset_attribute(attribute)
      send("#{attribute}=", 0)
    end

    def attribute_highest?(attribute)
      send(attribute) > 100
    end
end

person = Person.new
person.age = 110
person.age_highest?  # true
person.reset_age     # 0
person.age_highest?  # false

使い方よくわからなかったけど、この図で理解できた。

 

2 Callbacksモジュール

class Person
  extend ActiveModel::Callbacks

  define_model_callbacks :update

  before_update :reset_me

  def update
    run_callbacks(:update) do
      # updateメソッドがオブジェクトに対して呼び出されるとこのメソッドが呼び出される
    end
  end

  def reset_me
    # このメソッドは、before_updateコールバックで定義されているとおり、updateメソッドがオブジェクトに対して呼び出される直前に呼び出される。
  end
end

 updateだけじゃなく、create等でもいける。 run_callbacksの中で実行するのがミソか

3 Conversionモジュール

4 Dirtyモジュール

5 Validationsモジュール

6 Namingモジュール

7 Modelモジュール

ActiveModel::Modelincludeすると、以下のような機能を使えるようになります。

  • モデル名の調査
  • 変換
  • 翻訳
  • バリデーション

persisted? は オブジェクトが保存済みかどうかを確認するメソッド

8 シリアライズ

class Person
  include ActiveModel::Serialization

  attr_accessor :name

  def attributes
    {'name' => nil}
  end
end

上のようにすることで、serializable_hashを使ってオブジェクトのシリアライズ化ハッシュにアクセスできるようになります。

person = Person.new
person.serializable_hash   # => {"name"=>nil}
person.name = "Bob"
person.serializable_hash   # => {"name"=>"Bob"}

qiita.com

 

シリアライズはよくないらしい。

9 Translationモジュール

Person.human_attribute_name('name') # => "Name"

よく使うやつ

10 Lintテスト

11 SecurePasswordモジュール

bcryptっていうgemに依存している

感想

ActiveModelことができることを一言で表すと、

 

「active record の実現を助けてくれるモジュール群」