通知に〇〇前表示をさせる
こんにちは、ぐっちと申します。
よくアプリの通知欄の下などに、「2日前」や「1時間前」などの時間表示がありますが、それを実装したく思い調べてみました。
やっぱり複雑なコードが必要なのかと思ったいましたが、簡単に実装出来てしまいました。
time_ago_in_wordsメソッドというものがあり、それを使用します。
まず、config/locales/ja.yml を作成します。そのファイルに
ja:
datetime:
distance_in_words:
half_a_minute: "30秒前後"
less_than_x_seconds:
one: "1秒"
other: "%{count}秒"
x_seconds:
one: "1秒"
other: "%{count}秒"
less_than_x_minutes:
one: "1分"
other: "%{count}分"
x_minutes:
one: "約1分"
other: "%{count}分"
about_x_hours:
one: "約1時間"
other: "約%{count}時間"
x_days:
one: "1日"
other: "%{count}日"
about_x_months:
one: "約1ヶ月"
other: "約%{count}ヶ月"
x_months:
one: "1ヶ月"
other: "%{count}ヶ月"
almost_x_years:
one: "1年弱"
other: "%{count}年弱"
about_x_years:
one: "約1年"
other: "約%{count}年"
over_x_years:
one: "1年以上"
other: "%{count}年以上"
を記述します
次に、config/application.rb に
を記述します
これでビューに
<%= time_ago_in_words(hoge.created_at) %>前
を記述するだけでレコードが作成されてからの時間が表示される様になります。
調べると本当に色々な便利な機能が出てきて、驚きと共に勉強になります。
ここまで読んでくださり、ありがとうございました。
ツイッターで日々の学習をつぶやいています