File: repeater_weekday.rb

package info (click to toggle)
ruby-chronic 0.6.7-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 384 kB
  • sloc: ruby: 3,726; makefile: 2
file content (85 lines) | stat: -rw-r--r-- 1,828 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
module Chronic
  class RepeaterWeekday < Repeater #:nodoc:
    DAY_SECONDS = 86400 # (24 * 60 * 60)
    DAYS = {
      :sunday => 0,
      :monday => 1,
      :tuesday => 2,
      :wednesday => 3,
      :thursday => 4,
      :friday => 5,
      :saturday => 6
    }

    def initialize(type)
      super
    end

    def next(pointer)
      super

      direction = pointer == :future ? 1 : -1

      if !@current_weekday_start
        @current_weekday_start = Chronic.construct(@now.year, @now.month, @now.day)
        @current_weekday_start += direction * DAY_SECONDS

        until is_weekday?(@current_weekday_start.wday)
          @current_weekday_start += direction * DAY_SECONDS
        end
      else
        loop do
          @current_weekday_start += direction * DAY_SECONDS
          break if is_weekday?(@current_weekday_start.wday)
        end
      end

      Span.new(@current_weekday_start, @current_weekday_start + DAY_SECONDS)
    end

    def this(pointer = :future)
      super

      case pointer
      when :past
        self.next(:past)
      when :future, :none
        self.next(:future)
      end
    end

    def offset(span, amount, pointer)
      direction = pointer == :future ? 1 : -1

      num_weekdays_passed = 0; offset = 0
      until num_weekdays_passed == amount
        offset += direction * DAY_SECONDS
        num_weekdays_passed += 1 if is_weekday?((span.begin+offset).wday)
      end

      span + offset
    end

    def width
      DAY_SECONDS
    end

    def to_s
      super << '-weekday'
    end

    private

    def is_weekend?(day)
      day == symbol_to_number(:saturday) || day == symbol_to_number(:sunday)
    end

    def is_weekday?(day)
      !is_weekend?(day)
    end

    def symbol_to_number(sym)
      DAYS[sym] || raise("Invalid symbol specified")
    end
  end
end