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
|
# File 'lib/activerecord_chronological_records.rb', line 2
def has_chronological_records(*options)
if options.empty?
start_column, end_column = :start_date, :end_date
else
start_column, end_column = options[0], options[1]
end
dealing_with_dates = columns.select{|c| [start_column, end_column].map(&:to_s).include? c.name}.all?{|c| c.type == :date}
query_start_column = "#{table_name}.#{start_column}"
query_end_column = "#{table_name}.#{end_column}"
same_record_lookup = "#{self}.where(:#{primary_key} => self.#{primary_key})"
self.instance_eval " def effective_at(date)\n where(\"(\#{query_start_column} <= :date OR \#{query_start_column} IS NULL) AND (\#{query_end_column} >= :date OR \#{query_end_column} IS NULL)\", :date => \#{dealing_with_dates ? 'date.to_date' : 'date'})\n end\n\n def current\n effective_at(Time.now)\n end\n"
self.class_eval " def effective_at(date)\n \#{same_record_lookup}.effective_at(date).first\n end\n\n def earliest\n \#{same_record_lookup}.order(\"\#{query_start_column} ASC\").first\n end\n\n def latest\n \#{same_record_lookup}.order(\"\#{query_start_column} DESC\").first\n end\n\n def previous\n effective_at(\#{start_column} - 1.day)\n end\n\n def next\n effective_at(\#{end_column} + 1.day)\n end\n\n def current\n effective_at(Time.now)\n end\n\n def current?\n (\#{start_column}.blank? || \#{start_column}.to_time <= Time.now) && (\#{end_column}.blank? || \#{end_column}.to_time >= Time.now)\n end\n"
end
|