Class: Freq

Inherits:
Object
  • Object
show all
Defined in:
lib/freq.rb

Overview

Class that defines a frequency for a recurring thing.

Note: this class does not properly handle months and years.

Constant Summary collapse

SECOND =
1
MINUTE =
SECOND * 60
HOUR =
MINUTE * 60
DAY =
HOUR * 24
WEEK =
DAY * 7
MONTH =
DAY * 30
YEAR =
DAY * 365

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(period, times) ⇒ Freq

Returns a new instance of Freq.



18
19
20
21
# File 'lib/freq.rb', line 18

def initialize(period, times)
  @period = period
  @times = times
end

Instance Attribute Details

#periodObject

Returns the value of attribute period.



15
16
17
# File 'lib/freq.rb', line 15

def period
  @period
end

#timesObject

Returns the value of attribute times.



16
17
18
# File 'lib/freq.rb', line 16

def times
  @times
end

Class Method Details

.parse(str) ⇒ Object



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
# File 'lib/freq.rb', line 33

def self.parse(str)
  times = 1
  period = 0
  multiplier = 1
  
  words = str.downcase.split
  words.each_with_index do |word, i|
    case word
    when 'every'
      if words[i+1] == 'other'
        multiplier = 2
      end
      if words[i+1] =~ /\d+/
        multiplier = words[i+1].to_i
      end
    when 'twice' then times = 2
    when /times?/
      times = word_to_number(words[i-1])
    when /seconds?/ then period = SECOND
    when /minutes?/ then period = MINUTE
    when /hours?/ then period = HOUR
    when /days?/ then period = DAY
    when /weeks?/ then period = WEEK
    when /months?/ then period = MONTH
    when /years?/ then period = YEAR
    end
  end
  
  new(period * multiplier, times)
end

.word_to_number(word) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/freq.rb', line 64

def self.word_to_number(word)
  if n = word.to_i
    if n == 0
      return 0 if word == '0' || word == 'zero'
    else
      return n
    end
  end
  
  irregular = {
    'zero' => 0,
    'one' => 1,
    'two' => 2,
    'three' => 3,
    'four' => 4,
    'five' => 5,
    'six' => 6,
    'seven' => 7,
    'eight' => 8,
    'nine' => 9,
    'ten' => 10,
    'eleven' => 11,
    'twelve' => 12,
    'thirteen' => 13,
    'fourteen' => 14,
    'fifteen' => 15,
    'sixteen' => 16,
    'seventeen' => 17,
    'eighteen' => 18,
    'nineteen' => 19
  }
  return irregular[word] if irregular[word]
end

Instance Method Details

#next(t) ⇒ Object

Apply the frequency to the given timestamp to get the next occurrence.



29
30
31
# File 'lib/freq.rb', line 29

def next(t)
  Time.at(t + to_seconds)
end

#to_secondsObject



23
24
25
26
# File 'lib/freq.rb', line 23

def to_seconds
  return 0 if times == 0 || period == 0
  period / times
end