はじめに
今週の月曜日から日曜日の日付を指定し、データを取得する方法を実装しました。
読書を習慣化を促すアプリにて、今週の読書状況を表すためです。
調べたことをもとに自分で実装してみたので投稿します。
環境
- Rails 6.1.3
- Ruby 2.7.2
実装
Date#prev_occurring
とDate#next_occurring
を使用して実装します。
<手順>
- 今日の曜日を取得
- 今週の月曜日と日曜日の日付を取得し、変数
from
to
に代入 - 今日の曜日によって条件分岐
- データを取得
1. 今日の曜日を取得
today = Date.today
day_of_the_week = today.wday
RubyのTimeクラスのwday
メソッドを利用してます。
曜日を0を日曜日とし、6(土曜日)までの整数を返してくれます。
(日:0, 月:1, 火:2, 水:3, 木:4, 金:5, 土:6)
2. 今週の月曜日と日曜日の日付を取得し、変数from
to
に代入
from = today.prev_occurring(:monday)
to = today.next_occurring(:sunday)
prev_occurring
で過去の今週の月曜日の日付を、
next_occurring
で未来の今週の日曜日の日付を取得しています。
ちなみにこんな感じに返ってきます。すごい!
irb(main)> today = Date.today
=> Wed, 29 Sep 2021
irb(main)> from = today.prev_occurring(:monday)
=> Mon, 27 Sep 2021
irb(main)> to = today.next_occurring(:sunday)
=> Sun, 03 Oct 2021
3. 今日の曜日によって微調整
上記だけだと、
- 今日が月曜日のとき、先週の月曜日の日付
- 今日が日曜日のとき、来週の日曜日の日付
をそれぞれ取ってきてしまいます。
必要なのはあくまで今週の日付ですので、上記2点だけ条件分岐をします。
if day_of_the_week == 1 # 今日が月曜日
from = today
elsif day_of_the_week == 0 #今日が日曜日
to = today
end
4. データを取得
from...to
でDate型のカラムの範囲を指定できます。
tasks = Task.where(read_on: from...to)
完成
today = Date.today
day_of_the_week = today.wday
from = today.prev_occurring(:monday)
to = today.next_occurring(:sunday)
if day_of_the_week == 1
from = today
elsif day_of_the_week == 0
to = today
end
tasks = Task.where(read_on: from...to)
あとはデータを使って処理を書いたり、
from...to
を使って日付ごとに処理したりできます。
以上、初投稿でした!
より良い方法等ありましたら是非コメントお願い致します。
参考
-
Date#prev_occurring
とDate#next_occurring
の使い方
https://qiita.com/hotu_ta/items/4bd67c085cd46d71999b -
Time#wday
リファレンス
https://docs.ruby-lang.org/ja/2.7.0/class/Time.html#I_WDAY