Class: Cyclical::WeekdaysFilter

Inherits:
Object
  • Object
show all
Defined in:
lib/cyclical/filters/weekdays_filter.rb

Constant Summary collapse

WEEKDAYS =
{
  :su => 0, :sun => 0, :sunday => 0,
  :mo => 1, :mon => 1, :monday => 1,
  :tu => 2, :tue => 2, :tuesday => 2,
  :we => 3, :wed => 3, :wednesday => 3,
  :th => 4, :thu => 4, :thursday => 4,
  :fr => 5, :fri => 5, :friday => 5,
  :sa => 6, :sat => 6, :saturday => 6
}
WEEKDAY_NAMES =
[:su, :mo, :tu, :we, :th, :fr, :sa]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*weekdays) ⇒ WeekdaysFilter

Returns a new instance of WeekdaysFilter.

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/cyclical/filters/weekdays_filter.rb', line 18

def initialize(*weekdays)
  @rule = weekdays.shift if weekdays.first.is_a?(Rule)

  raise ArgumentError, "Specify at least one weekday" if weekdays.empty?
  @ordered_weekdays = {}

  if weekdays.last.respond_to?(:has_key?)
    raise ArgumentError, "No recurrence rule given for ordered weekdays filter" if @rule.nil?

    weekdays.last.each do |day, orders|
      day = day.is_a?(Integer) ? day : WEEKDAYS[day]
      orders = [orders] unless orders.respond_to?(:each)

      @ordered_weekdays[WEEKDAY_NAMES[day]] = orders.sort
    end
    weekdays = weekdays[0..-2]
  end

  @weekdays = weekdays.map { |w| w.is_a?(Integer) ? w : WEEKDAYS[w.to_sym] }.sort
end

Instance Attribute Details

#ordered_weekdaysObject (readonly)

Returns the value of attribute ordered_weekdays.



16
17
18
# File 'lib/cyclical/filters/weekdays_filter.rb', line 16

def ordered_weekdays
  @ordered_weekdays
end

#ruleObject (readonly)

Returns the value of attribute rule.



16
17
18
# File 'lib/cyclical/filters/weekdays_filter.rb', line 16

def rule
  @rule
end

#weekdaysObject (readonly)

Returns the value of attribute weekdays.



16
17
18
# File 'lib/cyclical/filters/weekdays_filter.rb', line 16

def weekdays
  @weekdays
end

Instance Method Details

#match?(date) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
# File 'lib/cyclical/filters/weekdays_filter.rb', line 39

def match?(date)
  return true if weekdays.include?(date.wday)

  day = WEEKDAY_NAMES[date.wday]
  return false if ordered_weekdays[day].nil?

  first, occ, max = order_in_interval(date)

  return (ordered_weekdays[day].include?(occ) || ordered_weekdays[day].include?(occ - max - 1))
end

#next(date) ⇒ Object

FIXME - this can probably be calculated



55
56
57
58
59
60
61
# File 'lib/cyclical/filters/weekdays_filter.rb', line 55

def next(date)
  until match?(date)
    date += 1.day
  end

  date
end

#previous(date) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/cyclical/filters/weekdays_filter.rb', line 63

def previous(date)
  until match?(date)
    date -= 1.day
  end

  date
end

#stepObject



50
51
52
# File 'lib/cyclical/filters/weekdays_filter.rb', line 50

def step
  1.day
end