このようなヘルパーは既に存在し、Rails に組み込まれています。
http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words
time_ago_in_words(5.days.ago)
=> "5 days"
編集:
言葉遣いをカスタマイズしたい場合は、カスタムI18n
ロケールを作成できます。たとえば、time_ago という名前のロケールを作成しましたconfig/locales/time_ago.yml
。
time_ago:
datetime:
distance_in_words:
half_a_minute: "half a minute"
less_than_x_seconds:
one: "less than 1 second"
other: "less than %{count} seconds"
x_seconds:
one: "1 second"
other: "%{count} seconds"
less_than_x_minutes:
one: "less than a minute"
other: "less than %{count} minutes"
x_minutes:
one: "1 min"
other: "%{count} mins"
about_x_hours:
one: "about 1 hour"
other: "about %{count} hours"
x_days:
one: "1 day"
other: "%{count} days"
about_x_months:
one: "about 1 month"
other: "about %{count} months"
x_months:
one: "1 month"
other: "%{count} months"
about_x_years:
one: "about 1 year"
other: "about %{count} years"
over_x_years:
one: "over 1 year"
other: "over %{count} years"
almost_x_years:
one: "almost 1 year"
other: "almost %{count} years"
distance_of_time_in_words
これで、ロケールを次のように使用できます。
# distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
distance_of_time_in_words(5.minutes.ago, Time.now, true, {:locale => "time_ago"})
=> "5 mins"
もちろん、これを追加してconfig/locales/en.yml
、アプリケーション全体で完全にオーバーライドすることもできます。これにより、time_ago_in_words
上記のように呼び出すことができます!