class UsBankHolidays::Month

Utility class to make it easier to work with a particular month. It represents a month of a specific year.

Attributes

month[R]
year[R]

Public Class Methods

new(year, month) click to toggle source

Initializes an instance from a year and a month. Raises an error if the month is not in the allowed range, i.e. it must be between 1 and 12 inclusive.

# File lib/us_bank_holidays/month.rb, line 11
def initialize(year, month)
  if month < 1 || month > 12
    raise ArgumentError, "Month is out of range, must be between 1 and 12, got #{month}"
  end
  @month = month
  @year  = year
  @weeks = []
  init_month
end

Public Instance Methods

contains?(date) click to toggle source

Returns true if the given month contains the given date, false otherwise.

# File lib/us_bank_holidays/month.rb, line 60
def contains?(date)
  year == date.year && month == date.month
end
to_s() click to toggle source
# File lib/us_bank_holidays/month.rb, line 21
def to_s
  @to_s ||= begin
    wks = @weeks.map { |w|
      w.map { |d|
        if d.nil?
          '  '
        elsif d.day < 10
          " #{d.day}"
        else
          "#{d.day}"
        end
      }.join(' ')
    }.join("\n")
    "Su Mo Tu We Th Fr Sa\n#{wks}\n"
  end
end

Private Instance Methods

init_first_week(start_date) click to toggle source
# File lib/us_bank_holidays/month.rb, line 80
def init_first_week(start_date)
  offset = []
  start_date.wday.times { offset << nil }
  offset
end
init_month() click to toggle source
# File lib/us_bank_holidays/month.rb, line 66
def init_month
  current_date = Date.new(year, month, 1)
  week = init_first_week(current_date)
  while current_date.month == month
    week << current_date
    current_date += 1
    if week.size == 7 || current_date.month != month
      @weeks << week.freeze
      week = [] if contains?(current_date)
    end
  end
  @weeks.freeze
end