Class: IceCube::DayOfWeekValidation

Inherits:
Validation show all
Defined in:
lib/ice_cube/validations/day_of_week.rb

Constant Summary

Constants inherited from Validation

Validation::NUMBER_SUFFIX

Instance Method Summary collapse

Methods inherited from Validation

#adjust, #nice_numbers, #sentence

Constructor Details

#initialize(rule) ⇒ DayOfWeekValidation

Returns a new instance of DayOfWeekValidation.



5
6
7
8
# File 'lib/ice_cube/validations/day_of_week.rb', line 5

def initialize(rule)
  @days_of_week = rule.validations[:day_of_week]
  @rule = rule
end

Instance Method Details

#closest(date) ⇒ Object

note - temporary implementation



22
23
24
25
26
27
28
# File 'lib/ice_cube/validations/day_of_week.rb', line 22

def closest(date)
  return nil if !@days_of_week || @days_of_week.empty?
  goal = date
  while goal += IceCube::ONE_DAY
    return adjust(goal, date) if validate(goal)
  end
end

#to_icalObject



39
40
41
42
43
44
45
# File 'lib/ice_cube/validations/day_of_week.rb', line 39

def to_ical
  representation = 'BYDAY='
  representation << @days_of_week.map do |day, occ|
    occ.map { |o| o.to_s + IceCube::ICAL_DAYS[day] }.join(',')
  end.join(',')
  representation
end

#to_sObject



30
31
32
33
34
35
36
37
# File 'lib/ice_cube/validations/day_of_week.rb', line 30

def to_s
  representation = ''
  representation << 'on the '
  representation << @days_of_week.map do |day, occ| 
    nice_numbers(occ) << ' ' << Date::DAYNAMES[day] << (occ.size != 1 ? 's' : '') unless @days_of_week.empty?
  end.join(' and the ')
  representation
end

#validate(date) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/ice_cube/validations/day_of_week.rb', line 10

def validate(date)
  # is it even one of the valid days?
  return true if !@days_of_week || @days_of_week.empty?
  return false unless @days_of_week.has_key?(date.wday) #shortcut
  # does this fall on one of the occurrences?
  first_occurrence = ((7 - Time.utc(date.year, date.month, 1).wday) + date.wday) % 7 + 1 #day of first occurrence of a wday in a month
  this_weekday_in_month_count = ((TimeUtil.days_in_month(date) - first_occurrence + 1) / 7.0).ceil #how many of these in the month
  nth_occurrence_of_weekday = (date.mday - first_occurrence) / 7 + 1 #what occurrence of the weekday is +date+
  @days_of_week[date.wday].include?(nth_occurrence_of_weekday) || @days_of_week[date.wday].include?(nth_occurrence_of_weekday - this_weekday_in_month_count - 1)
end