Techioz Blog

Rails は 2 つの日付の違いを見つけます

概要

ユーザーがアプリのメンバーになっている期間を計算したいと考えています。次のように表示する必要があります:

ユーザー会員 2y,9m

そのために、User モデル内にメソッドを作成しました。

  def member_for
    #calculate number of months
    month = (Time.current.year * 12 + Time.current.month) - (created_at.year * 12 + created_at.month)
    #an array [years, months]
    result = month.divmod(12)

    if result[0].zero? && result[1].nonzero?
      "User member for #{result[1]}m"
    elsif result[1].zero? && result[0].nonzero?
      "User member for #{result[0]}y"
    elsif result[0].zero? && result[1].zero?
      'User member for 1m'
    else
      "User member for #{result[0]}y, #{result[1]}m"
    end
  end

しかし、正直に言って、このコードは臭いです。Rails6 には、これをより適切に実行して、コードをもう少しきれいに見せるための組み込みメソッドはありませんか?

解決策

これには ActiveSupport::Duration を使用できます。必要なのは、時差を ActiveSupport::Duration.build メソッドに渡すことだけです。 例えば:

time_diff = Time.now - 1000.days.ago
ActiveSupport::Duration.build(time_diff.to_i)         # 2 years, 8 months, 3 weeks, 5 days, 28 minutes, and 47 seconds 
ActiveSupport::Duration.build(time_diff.to_i).parts   # 2 years, 8 months, 3 weeks, 5 days, 28 minutes, and 47 seconds