ice_cube 0.6.10 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. data/lib/ice_cube/builders/hash_builder.rb +27 -0
  2. data/lib/ice_cube/builders/ical_builder.rb +59 -0
  3. data/lib/ice_cube/builders/string_builder.rb +74 -0
  4. data/lib/ice_cube/errors/count_exceeded.rb +7 -0
  5. data/lib/ice_cube/errors/until_exceeded.rb +7 -0
  6. data/lib/ice_cube/rule.rb +86 -140
  7. data/lib/ice_cube/rules/daily_rule.rb +5 -27
  8. data/lib/ice_cube/rules/hourly_rule.rb +6 -26
  9. data/lib/ice_cube/rules/minutely_rule.rb +5 -25
  10. data/lib/ice_cube/rules/monthly_rule.rb +6 -30
  11. data/lib/ice_cube/rules/secondly_rule.rb +5 -26
  12. data/lib/ice_cube/rules/weekly_rule.rb +5 -36
  13. data/lib/ice_cube/rules/yearly_rule.rb +8 -34
  14. data/lib/ice_cube/schedule.rb +262 -189
  15. data/lib/ice_cube/single_occurrence_rule.rb +28 -0
  16. data/lib/ice_cube/time_util.rb +202 -76
  17. data/lib/ice_cube/validated_rule.rb +107 -0
  18. data/lib/ice_cube/validations/count.rb +56 -0
  19. data/lib/ice_cube/validations/daily_interval.rb +51 -0
  20. data/lib/ice_cube/validations/day.rb +45 -29
  21. data/lib/ice_cube/validations/day_of_month.rb +45 -43
  22. data/lib/ice_cube/validations/day_of_week.rb +59 -41
  23. data/lib/ice_cube/validations/day_of_year.rb +49 -43
  24. data/lib/ice_cube/validations/hour_of_day.rb +43 -29
  25. data/lib/ice_cube/validations/hourly_interval.rb +50 -0
  26. data/lib/ice_cube/validations/lock.rb +47 -0
  27. data/lib/ice_cube/validations/minute_of_hour.rb +43 -30
  28. data/lib/ice_cube/validations/minutely_interval.rb +50 -0
  29. data/lib/ice_cube/validations/month_of_year.rb +40 -29
  30. data/lib/ice_cube/validations/monthly_interval.rb +47 -0
  31. data/lib/ice_cube/validations/schedule_lock.rb +41 -0
  32. data/lib/ice_cube/validations/second_of_minute.rb +40 -29
  33. data/lib/ice_cube/validations/secondly_interval.rb +50 -0
  34. data/lib/ice_cube/validations/until.rb +49 -0
  35. data/lib/ice_cube/validations/weekly_interval.rb +50 -0
  36. data/lib/ice_cube/validations/yearly_interval.rb +45 -0
  37. data/lib/ice_cube/version.rb +2 -2
  38. data/lib/ice_cube.rb +63 -37
  39. data/spec/spec_helper.rb +13 -0
  40. metadata +47 -8
  41. data/lib/ice_cube/rule_occurrence.rb +0 -100
  42. data/lib/ice_cube/validation.rb +0 -44
  43. data/lib/ice_cube/validation_types.rb +0 -137
@@ -0,0 +1,27 @@
1
+ module IceCube
2
+
3
+ class HashBuilder
4
+
5
+ def initialize(rule = nil)
6
+ @hash = { :validations => {}, :rule_type => rule.class.name }
7
+ end
8
+
9
+ def validations
10
+ @hash[:validations]
11
+ end
12
+
13
+ def []=(key, value)
14
+ @hash[key] = value
15
+ end
16
+
17
+ def validations_array(type)
18
+ validations[type] ||= []
19
+ end
20
+
21
+ def to_hash
22
+ @hash
23
+ end
24
+
25
+ end
26
+
27
+ end
@@ -0,0 +1,59 @@
1
+ module IceCube
2
+
3
+ class IcalBuilder
4
+
5
+ ICAL_DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']
6
+
7
+ def initialize
8
+ @hash = {}
9
+ end
10
+
11
+ def self.fixnum_to_ical_day(num)
12
+ ICAL_DAYS[num]
13
+ end
14
+
15
+ def [](key)
16
+ @hash[key] ||= []
17
+ end
18
+
19
+ # Build for a single rule entry
20
+ def to_s
21
+ arr = []
22
+ if freq = @hash.delete('FREQ')
23
+ arr << "FREQ=#{freq.join(',')}"
24
+ end
25
+ arr.concat(@hash.map do |key, value|
26
+ if value.is_a?(Array)
27
+ "#{key}=#{value.join(',')}"
28
+ end
29
+ end.compact)
30
+ arr.join(';')
31
+ end
32
+
33
+ def self.ical_utc_format(time)
34
+ time = time.dup.utc
35
+ "#{time.strftime('%Y%m%dT%H%M%SZ')}" # utc time
36
+ end
37
+
38
+ def self.ical_format(time, force_utc)
39
+ time = time.dup.utc if force_utc
40
+ if time.utc?
41
+ ":#{time.strftime('%Y%m%dT%H%M%SZ')}" # utc time
42
+ else
43
+ ";TZID=#{time.strftime('%Z:%Y%m%dT%H%M%S')}" # local time specified
44
+ end
45
+ end
46
+
47
+ def self.ical_duration(duration)
48
+ hours = duration / 3600; duration %= 3600
49
+ minutes = duration / 60; duration %= 60
50
+ repr = ''
51
+ repr << "#{hours}H" if hours > 0
52
+ repr << "#{minutes}M" if minutes > 0
53
+ repr << "#{duration}S" if duration > 0
54
+ "PT#{repr}"
55
+ end
56
+
57
+ end
58
+
59
+ end
@@ -0,0 +1,74 @@
1
+ module IceCube
2
+
3
+ class StringBuilder
4
+
5
+ attr_writer :base
6
+
7
+ def initialize
8
+ @types = {}
9
+ end
10
+
11
+ def piece(type, prefix = nil, suffix = nil)
12
+ @types[type] ||= []
13
+ end
14
+
15
+ def to_s
16
+ str = @base || ''
17
+ res = @types.map do |type, segments|
18
+ if f = self.class.formatter(type)
19
+ str << ' ' + f.call(segments)
20
+ else
21
+ next if segments.empty?
22
+ str << ' ' + self.class.sentence(segments)
23
+ end
24
+ end
25
+ str
26
+ end
27
+
28
+ class << self
29
+
30
+ def formatter(type)
31
+ @formatters[type]
32
+ end
33
+
34
+ def register_formatter(type, &formatter)
35
+ @formatters ||= {}
36
+ @formatters[type] = formatter
37
+ end
38
+
39
+ end
40
+
41
+ class << self
42
+
43
+ NUMBER_SUFFIX = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
44
+ SPECIAL_SUFFIX = { 11 => 'th', 12 => 'th', 13 => 'th', 14 => 'th' }
45
+
46
+ # influenced by ActiveSupport's to_sentence
47
+ def sentence(array)
48
+ case array.length
49
+ when 0 ; ''
50
+ when 1 ; array[0].to_s
51
+ when 2 ; "#{array[0]} and #{array[1]}"
52
+ else ; "#{array[0...-1].join(', ')}, and #{array[-1]}"
53
+ end
54
+ end
55
+
56
+ def nice_number(number)
57
+ if number == -1
58
+ 'last'
59
+ elsif number < -1
60
+ suffix = SPECIAL_SUFFIX.include?(number) ?
61
+ SPECIAL_SUFFIX[number] : NUMBER_SUFFIX[number.abs % 10]
62
+ number.abs.to_s << suffix << ' to last'
63
+ else
64
+ suffix = SPECIAL_SUFFIX.include?(number) ?
65
+ SPECIAL_SUFFIX[number] : NUMBER_SUFFIX[number.abs % 10]
66
+ number.to_s << suffix
67
+ end
68
+ end
69
+
70
+ end
71
+
72
+ end
73
+
74
+ end
@@ -0,0 +1,7 @@
1
+ module IceCube
2
+
3
+ # An exception for when a count on a Rule is passed
4
+ class CountExceeded < Exception
5
+ end
6
+
7
+ end
@@ -0,0 +1,7 @@
1
+ module IceCube
2
+
3
+ # An exception for when an until date on a Rule is passed
4
+ class UntilExceeded < Exception
5
+ end
6
+
7
+ end
data/lib/ice_cube/rule.rb CHANGED
@@ -1,163 +1,109 @@
1
+ require 'yaml'
2
+
1
3
  module IceCube
2
-
4
+
3
5
  class Rule
4
-
5
- attr_reader :occurrence_count, :until_date
6
-
7
- include ValidationTypes
8
6
 
9
- def to_hash
10
- hash = Hash.new
11
- hash[:rule_type] = self.class.name
12
- hash[:interval] = @interval
13
- hash[:until] = @until_date ? TimeUtil.serialize_time(@until_date) : @until_date
14
- hash[:count] = @occurrence_count
15
- hash[:validations] = @validations
16
- hash
17
- end
18
-
19
- def self.from_hash(hash)
20
- rule = hash[:rule_type].split('::').inject(Object) { |namespace, const_name| namespace.const_get(const_name) }.new(hash[:interval])
21
- rule.count(hash[:count]) if hash[:count]
22
- rule.until(hash[:until]) if hash[:until]
23
- hash[:validations].each do |validation, data|
24
- data.is_a?(Array) ? rule.send(validation, *data) : rule.send(validation, data)
25
- end
26
- rule
27
- end
28
-
29
- def to_yaml(options = {})
30
- to_hash.to_yaml(options)
7
+ attr_reader :uses
8
+
9
+ # Is this a terminating schedule?
10
+ def terminating?
11
+ until_time || occurrence_count
31
12
  end
32
13
 
33
- def self.from_yaml(str)
34
- from_hash(YAML::load(str))
14
+ def ==(rule)
15
+ hash = to_hash
16
+ hash && hash == rule.to_hash
35
17
  end
36
-
37
- # create a new daily rule
38
- def self.daily(interval = 1)
39
- DailyRule.new(interval)
18
+
19
+ def hash
20
+ h = to_hash
21
+ h.nil? ? super : h.hash
40
22
  end
41
23
 
42
- # create a new weekly rule
43
- def self.weekly(interval = 1)
44
- WeeklyRule.new(interval)
24
+ # Expected to be overridden by subclasses
25
+ def to_ical
26
+ nil
45
27
  end
46
28
 
47
- # create a new monthly rule
48
- def self.monthly(interval = 1)
49
- MonthlyRule.new(interval)
29
+ # Yaml implementation
30
+ def to_yaml(*args)
31
+ defined?(Psych) ? Psych::dump(to_hash) : YAML::dump(to_hash, *args)
50
32
  end
51
33
 
52
- # create a new yearly rule
53
- def self.yearly(interval = 1)
54
- YearlyRule.new(interval)
34
+ # From yaml
35
+ def self.from_yaml(yaml)
36
+ from_hash defined?(Psych) ? Psych::load(yaml) : YAML::load(yaml)
55
37
  end
56
-
57
- # create a new hourly rule
58
- def self.hourly(interval = 1)
59
- HourlyRule.new(interval)
38
+
39
+ # Expected to be overridden by subclasses
40
+ def to_hash
41
+ nil
60
42
  end
61
-
62
- # create a new minutely rule
63
- def self.minutely(interval = 1)
64
- MinutelyRule.new(interval)
43
+
44
+ # Convert from a hash and create a rule
45
+ def self.from_hash(hash)
46
+ return nil unless match = hash[:rule_type].match(/\:\:(.+?)Rule/)
47
+ rule = IceCube::Rule.send(match[1].downcase.to_sym, hash[:interval] || 1)
48
+ rule.until(TimeUtil.deserialize_time(hash[:until])) if hash[:until]
49
+ rule.count(hash[:count]) if hash[:count]
50
+ hash[:validations] && hash[:validations].each do |key, value|
51
+ key = key.to_sym unless key.is_a?(Symbol)
52
+ value.is_a?(Array) ? rule.send(key, *value) : rule.send(key, value)
53
+ end
54
+ rule
65
55
  end
66
-
67
- # create a new secondly rule
68
- def self.secondly(interval = 1)
69
- SecondlyRule.new(interval)
56
+
57
+ # Reset the uses on the rule to 0
58
+ def reset
59
+ @uses = 0
70
60
  end
71
-
72
- # Set the time when this rule will no longer be effective
73
- def until(until_date)
74
- raise ArgumentError.new('Cannot specify until and count on the same rule') if @count #as per rfc
75
- @until_date = until_date
76
- self
61
+
62
+ def next_time(time, schedule, closing_time)
77
63
  end
78
-
79
- # set the number of occurrences after which this rule is no longer effective
80
- def count(count)
81
- raise ArgumentError.new('Argument must be a positive integer') unless Integer(count) && count >= 0
82
- @occurrence_count = count
83
- self
64
+
65
+ def on?(time, schedule)
66
+ next_time(time, schedule, time) == time
84
67
  end
85
-
86
- def validate_single_date(date)
87
- @validation_types.values.all? do |validation|
88
- response = validation.send(:validate, date)
89
- response.nil? || response
68
+
69
+ # Convenience methods for creating Rules
70
+ class << self
71
+
72
+ # Secondly Rule
73
+ def secondly(interval = 1)
74
+ SecondlyRule.new(interval)
90
75
  end
91
- end
92
-
93
- # The key to speed - extremely educated guesses
94
- # This spidering behavior will go through look for the next suggestion
95
- # by constantly moving the farthest back value forward
96
- def next_suggestion(date)
97
- # get the next date recommendation set
98
- suggestions = {};
99
- @validation_types.each { |k, validation| suggestions[k] = validation.send(:closest, date) }
100
- compact_suggestions = suggestions.values.compact
101
- # find the next date to go to
102
- if compact_suggestions.empty?
103
- attempt_count = 0
104
- loop do
105
- # keep going through rule suggestions
106
- next_date = self.default_jump(date, attempt_count += 1)
107
- return next_date if !next_date.nil? && validate_single_date(next_date)
108
- end
109
- else
110
- loop do
111
- compact_suggestions = suggestions.values.compact
112
- min_suggestion = compact_suggestions.min
113
- # validate all against the minimum
114
- return min_suggestion if validate_single_date(min_suggestion)
115
- # move anything that is the minimum to its next closest
116
- @validation_types.each do |k, validation|
117
- suggestions[k] = validation.send(:closest, min_suggestion) if min_suggestion == suggestions[k]
118
- end
119
- end
76
+
77
+ # Minutely Rule
78
+ def minutely(interval = 1)
79
+ MinutelyRule.new(interval)
120
80
  end
121
- end
122
-
123
- attr_reader :validations
124
-
125
- private
126
-
127
- def adjust(goal, date)
128
- return goal if goal.utc_offset == date.utc_offset
129
- goal - goal.utc_offset + date.utc_offset
130
- end
131
-
132
- # get a very meaningful string representation of this rule
133
- def to_s_base(singular, plural)
134
- representation = ''
135
- representation = (@interval == 1 ? singular : plural)
136
- representation << @validation_types.values.map { |v| ' ' + v.send(:to_s) }.join()
137
- representation << " #{occurrence_count} #{@occurrence_count == 1 ? 'time' : 'times'}" if @occurrence_count
138
- representation
139
- end
140
-
141
- # get the icalendar representation of this rule logic
142
- # Note: UNTIL dates are always in UTC as per iCalendar
143
- def to_ical_base
144
- representation = ''
145
- representation << ";INTERVAL=#{@interval}" if @interval > 1
146
- @validation_types.values.each do |v|
147
- representation << ';' << v.send(:to_ical)
148
- end
149
- representation << ";COUNT=#{@occurrence_count}" if @occurrence_count
150
- representation << ";UNTIL=#{TimeUtil.ical_utc_format(@until_date)}" if @until_date
151
- representation
152
- end
153
-
154
- # Set the interval for the rule. Depending on the type of rule,
155
- # interval means every (n) weeks, months, etc. starting on the start_date's
156
- def initialize(interval = 1)
157
- throw ArgumentError.new('Interval must be > 0') unless interval > 0
158
- @validations = {}
159
- @validation_types = {}
160
- @interval = interval
81
+
82
+ # Hourly Rule
83
+ def hourly(interval = 1)
84
+ HourlyRule.new(interval)
85
+ end
86
+
87
+ # Daily Rule
88
+ def daily(interval = 1)
89
+ DailyRule.new(interval)
90
+ end
91
+
92
+ # Weekly Rule
93
+ def weekly(interval = 1)
94
+ WeeklyRule.new(interval)
95
+ end
96
+
97
+ # Monthly Rule
98
+ def monthly(interval = 1)
99
+ MonthlyRule.new(interval)
100
+ end
101
+
102
+ # Yearly Rule
103
+ def yearly(interval = 1)
104
+ YearlyRule.new(interval)
105
+ end
106
+
161
107
  end
162
108
 
163
109
  end
@@ -1,34 +1,12 @@
1
1
  module IceCube
2
2
 
3
- class DailyRule < Rule
3
+ class DailyRule < ValidatedRule
4
4
 
5
- # TODO repair
6
- # Determine whether this rule occurs on a give date.
7
- def in_interval?(date, start_date)
8
- #make sure we're in a proper interval
9
- day_count = date.yday - start_date.yday
10
- day_count % @interval == 0
11
- end
12
-
13
- def to_ical
14
- 'FREQ=DAILY' << to_ical_base
15
- end
16
-
17
- def to_s
18
- to_s_base 'Daily', "Every #{@interval} days"
19
- end
20
-
21
- protected
22
-
23
- def default_jump(date, attempt_count = nil)
24
- goal = date + IceCube::ONE_DAY * @interval
25
- adjust(goal, date)
26
- end
27
-
28
- private
5
+ include Validations::DailyInterval
29
6
 
30
- def initialize(interval)
31
- super(interval)
7
+ def initialize(interval = 1)
8
+ interval(interval)
9
+ schedule_lock(:hour, :min, :sec)
32
10
  end
33
11
 
34
12
  end
@@ -1,34 +1,14 @@
1
1
  module IceCube
2
2
 
3
- class HourlyRule < Rule
3
+ class HourlyRule < ValidatedRule
4
4
 
5
- # Determine whether this rule occurs on a give date.
6
- def in_interval?(date, start_date)
7
- #make sure we're in a proper interval
8
- day_count = ((date - start_date) / IceCube::ONE_HOUR).to_i
9
- day_count % @interval == 0
10
- end
5
+ include Validations::HourlyInterval
11
6
 
12
- def to_ical
13
- 'FREQ=HOURLY' << to_ical_base
14
- end
15
-
16
- def to_s
17
- to_s_base 'Hourly', "Every #{@interval} hours"
7
+ def initialize(interval = 1)
8
+ interval(interval)
9
+ schedule_lock(:min, :sec)
18
10
  end
19
-
20
- protected
21
-
22
- def default_jump(date, attempt_count = nil)
23
- date + IceCube::ONE_HOUR * @interval
24
- end
25
-
26
- private
27
-
28
- def initialize(interval)
29
- super(interval)
30
- end
31
-
11
+
32
12
  end
33
13
 
34
14
  end
@@ -1,34 +1,14 @@
1
1
  module IceCube
2
2
 
3
- class MinutelyRule < Rule
3
+ class MinutelyRule < ValidatedRule
4
4
 
5
- # Determine whether this rule occurs on a give date.
6
- def in_interval?(date, start_date)
7
- #make sure we're in a proper interval
8
- day_count = ((date - start_date) / IceCube::ONE_MINUTE).to_i
9
- day_count % @interval == 0
10
- end
5
+ include Validations::MinutelyInterval
11
6
 
12
- def to_ical
13
- 'FREQ=MINUTELY' << to_ical_base
14
- end
15
-
16
- def to_s
17
- to_s_base 'Minutely', "Every #{@interval} minutes"
18
- end
19
-
20
- protected
21
-
22
- def default_jump(date, attempt_count = nil)
23
- date + IceCube::ONE_MINUTE
7
+ def initialize(interval = 1)
8
+ interval(interval)
9
+ schedule_lock(:sec)
24
10
  end
25
11
 
26
- private
27
-
28
- def initialize(interval)
29
- super(interval)
30
- end
31
-
32
12
  end
33
13
 
34
14
  end
@@ -1,38 +1,14 @@
1
1
  module IceCube
2
2
 
3
- class MonthlyRule < Rule
3
+ class MonthlyRule < ValidatedRule
4
4
 
5
- # Determine for a given date/start_date if this rule occurs or not.
6
- # Month rules occur if we're in a valid interval
7
- # and either (1) we're on a valid day of the week (ie: first sunday of the month)
8
- # or we're on a valid day of the month (1, 15, -1)
9
- # Note: Rollover is not implemented, so the 35th day of the month is invalid.
10
- def in_interval?(date, start_date)
11
- # make sure we're in the proper interval
12
- months_to_start_date = (date.month - start_date.month) + (date.year - start_date.year) * 12
13
- months_to_start_date % @interval == 0
14
- end
15
-
16
- def to_ical
17
- 'FREQ=MONTHLY' << to_ical_base
18
- end
19
-
20
- def to_s
21
- to_s_base 'Monthly', "Every #{@interval} months"
22
- end
23
-
24
- protected
25
-
26
- def default_jump(date, attempt_count = 1)
27
- TimeUtil.date_in_n_months(date, attempt_count * @interval)
28
- end
29
-
30
- private
5
+ include Validations::MonthlyInterval
31
6
 
32
- def initialize(interval)
33
- super(interval)
7
+ def initialize(interval = 1)
8
+ interval(interval)
9
+ schedule_lock(:day, :hour, :min, :sec)
34
10
  end
35
-
11
+
36
12
  end
37
13
 
38
14
  end
@@ -1,34 +1,13 @@
1
1
  module IceCube
2
2
 
3
- class SecondlyRule < Rule
3
+ class SecondlyRule < ValidatedRule
4
+
5
+ include Validations::SecondlyInterval
4
6
 
5
- # Determine whether this rule occurs on a give date.
6
- def in_interval?(date, start_date)
7
- #make sure we're in a proper interval
8
- day_count = date - start_date
9
- day_count % @interval == 0
7
+ def initialize(interval = 1)
8
+ interval(interval)
10
9
  end
11
10
 
12
- def to_ical
13
- 'FREQ=SECONDLY' << to_ical_base
14
- end
15
-
16
- def to_s
17
- to_s_base 'Secondly', "Every #{@interval} seconds"
18
- end
19
-
20
- protected
21
-
22
- def default_jump(date, attempt_count = nil)
23
- date + 1
24
- end
25
-
26
- private
27
-
28
- def initialize(interval)
29
- super(interval)
30
- end
31
-
32
11
  end
33
12
 
34
13
  end
@@ -1,45 +1,14 @@
1
1
  module IceCube
2
2
 
3
- class WeeklyRule < Rule
4
-
5
- # Determine whether or not this rule occurs on a given date.
6
- # Weekly rules occurs if we're in one of the interval weeks,
7
- # and we're in a valid day of the week.
8
- def in_interval?(date, start_date)
9
- #make sure we're in the right interval
10
- date = adjust(date, start_date)
3
+ class WeeklyRule < ValidatedRule
11
4
 
12
- date = Date.civil(date.year, date.month, date.day)
13
- start_date = Date.civil(start_date.year, start_date.month, start_date.day)
5
+ include Validations::WeeklyInterval
14
6
 
15
- #Move both to the start of their respective weeks,
16
- #and find the number of full weeks between them
17
- no_weeks = ((date - date.wday) - (start_date - start_date.wday)) / 7
18
-
19
- no_weeks % @interval == 0
20
- end
21
-
22
- def to_ical
23
- 'FREQ=WEEKLY' << to_ical_base
24
- end
25
-
26
- def to_s
27
- to_s_base 'Weekly', "Every #{@interval} weeks"
7
+ def initialize(interval = 1)
8
+ interval(interval)
9
+ schedule_lock(:wday, :hour, :min, :sec)
28
10
  end
29
-
30
- protected
31
-
32
- def default_jump(date, attempt_count = nil)
33
- goal = date + 7 * IceCube::ONE_DAY * @interval
34
- adjust(goal, date)
35
- end
36
-
37
- private
38
11
 
39
- def initialize(interval)
40
- super(interval)
41
- end
42
-
43
12
  end
44
13
 
45
14
  end