LoginSignup
3
0

More than 1 year has passed since last update.

Railsで1か月前の月初、1年前の年始、1週間前の週頭をできるだけ短いコードで書く

Last updated at Posted at 2023-05-11

やりたいこと

例えば、日付間隔が指定されたときに、以下のように日付を取りたいとする

日付間隔 取りたい日付
day 1日前 2023年5月10日(水) ⇒ 2023/5/9(火)
week 1週間前の月曜 2023年5月10日(水) ⇒ 2023/5/1(月)
month 1か月前の月初 2023年5月10日(水) ⇒ 2023/4/1(土)
year 1年前の年始 2023年5月10日(水) ⇒ 2022/1/1(土)

# span_typeに上表の"値"が入る
(Time.zone.today - 1.send(span_type)).send("beginning_of_#{span_type}").to_date

解説

send関数で指定した文字列の関数が呼ばれる。
例えば、Time.zone.today - 1.send('month')Time.zone.today - 1.monthと同義

ワンライナー大好き。

追記(2023.05.31)

@koki_73様からアドバイスいただきました!prev系関数を使う案です。

Time.current.send("prev_#{time_span}").send("beginning_of_#{time_span}").to_date
3
0
2

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
3
0