2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Railsでモデルから年齢の計算ロジックを別クラスに切り出す

Last updated at Posted at 2019-12-31

Railsでモデルから年齢の計算ロジックを別クラスに切り出す方法です。

前提

誕生日のカラムを持つモデルが存在する
e.g.

  • User モデルの birthed_on カラム
  • Employee モデルの birthed_on カラム

実装

Age というクラスを作成する

class Age
  def initialize(birthed_on)
    @birthed_on = birthed_on
    @value = calculate
  end

  def ==(other_age)
    to_i == other_age.to_i
  end

  def to_i
    value
  end

  def to_s
    value.to_s
  end

  def inspect
    to_i
  end

  private
  attr_reader :birthed_on, :value

  def calculate
    current = Time.current.strftime('%Y%m%d').to_i
    birthed = birthed_on.strftime('%Y%m%d').to_i
    (current - birthed) / 10_000
  end
end

年齢の計算ロジックを切り出すモデルに composed_of を追加する

# 例) ユーザモデル
class User < ApplicationRecord
  # 追加
  composed_of :age, mapping: [:birthed_on]
end

# 例) 従業員モデル
class Employee < ApplicationRecord
  # 追加
  composed_of :age, mapping: [:birthed_on]
end

# 例) 子どもモデル
class Child < ApplicationRecord
  # 追加
  composed_of :age, mapping: [:birthed_on]
end

確認

pry(main)> User.find(1).update(birthed_on: Date.parse('1990-01-01'))
=> true
pry(main)> User.find(1).age
=> 30

以上です。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?