Techioz Blog

現在の学年を調べる

概要

日付が現在の学年度内であるかどうかを確認したいです。そのために、現在の学年を決定する関数を作成しました。これを行うより良い方法はありますか?

# returns start and end date of current academic year
    def academic_year
         # assumption: an academic year is from sept 1st untill sept 1st
        start_date = Date.parse "#{Time.current.year}-09-01"
        end_date   = Date.parse "#{Time.current.year+1}-09-01"

        if Date.today < start_date
            start_date = Date.parse "#{Time.current.year-1}-09-01"
            end_date   = Date.parse "#{Time.current.year}-09-01"
        end

        {start: start_date, end: end_date}
    end

解決策

Ruby では Range#cover を使用しますか?

# see https://api.rubyonrails.org/classes/Date.html
start = Date.current.change(month: 9, day: 1)
academic_year = start..start.advance(years: 1)

academic_year.cover?(Date.current.change(month: 6, day: 15)) # false
academic_year.cover?(Date.current.change(month: 10, day: 2).advance(years: 2)) # false
academic_year.cover?(Date.current.change(month: 10, day: 2)) # true

ただし、通常はデータベース内の日付でクエリを実行する必要があり、その場合は範囲を .where に渡して BETWEEN クエリを作成します。

Order.where(placed: 2.years.ago..Time.current)
# SELECT "orders".* FROM "orders" WHERE "orders"."placed" BETWEEN $1 AND $2 LIMIT $3