-
Notifications
You must be signed in to change notification settings - Fork 1
/
subscription.rb
64 lines (52 loc) · 1.42 KB
/
subscription.rb
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
require 'rubygems'
require 'bundler/setup'
require 'active_support/core_ext'
class Subscription
cattr_reader :beginning
attr_accessor :interval, :start_date, :frequency
attr_reader :residue
@@beginning = Date.new(2014, 1, 1)
def initialize(args)
args.each { |k, v| instance_variable_set("@#{k}", v) unless v.nil? }
@frequency ||= :daily
compute_residue
end
def interval=(interval)
@interval = interval
compute_residue
end
def start_date=(start_date)
@start_date = start_date
compute_residue
end
def process_on?(date)
residue_for_date(date) == @residue
end
def next_processing_date(from_date)
from_date + ((@residue - residue_for_date(from_date)).modulo(@interval)).send(date_move_method)
end
def next_n_processing_dates(n, from_date)
first_next_processing_date = next_processing_date(from_date)
0.upto(n - 1).map { |i| first_next_processing_date + (@interval * i).send(date_move_method) }
end
private
def residue_for_date(date)
case @frequency
when :daily
(date - @@beginning).to_i.modulo(@interval)
when :monthly
((date.year - @@beginning.year) * 12 + (date.month - @@beginning.month)).modulo(@interval)
end
end
def compute_residue
@residue = residue_for_date(@start_date)
end
def date_move_method
@date_move_method ||= case @frequency
when :daily
:days
when :monthly
:months
end
end
end