Module: TimeCrisis::NthWeekday::ClassMethods

Included in:
Date, DateTime
Defined in:
lib/time_crisis/nth_weekday.rb

Constant Summary collapse

@@days_of_the_week =
{
        :sunday => 0,
        :monday => 1,
        :tuesday => 2,
        :wednesday => 3,
        :thursday => 4,
        :friday => 5,
        :saturday => 6
}

Instance Method Summary collapse

Instance Method Details

#nth_weekday(h = {}) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/time_crisis/nth_weekday.rb', line 14

def nth_weekday(h={})
  raise ArgumentError unless h[:nth]
  nth = h[:nth].to_s == 'last' ? 5 : h[:nth]
  
  unless h[:year] && h[:month] && h[:weekday]
    today = self.current
    
    h[:year] ||= today.year
    h[:month] ||= today.month
    h[:weekday] ||= today.wday
  end

  target_month = self.civil(h[:year], h[:month], 1)
  days_in_month = target_month.days_in_month
  target_weekday = h[:weekday].is_a?(Numeric) ? h[:weekday] : @@days_of_the_week[h[:weekday]]
  first_weekday = target_month.wday

  offset = target_weekday > 0 ? target_weekday - first_weekday + 1 : 7 - (first_weekday - 1)
  day = calculate_day_with_offset(nth, offset)

  while day > days_in_month
    nth = nth - 1
    day = calculate_day_with_offset(nth, offset)
  end

  self.civil(h[:year], h[:month], day)
end