Module: ActiverecordChronologicalRecords

Defined in:
lib/activerecord_chronological_records.rb

Instance Method Summary collapse

Instance Method Details

#has_chronological_records(*options) ⇒ Object



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 <<-EOS
    def effective_at(date)
      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'})
    end

    def current
      effective_at(Time.now)
    end
EOS

  self.class_eval <<-EOS
    def effective_at(date)
      #{same_record_lookup}.effective_at(date).first
    end

    def earliest
      #{same_record_lookup}.order("#{query_start_column} ASC").first
    end

    def latest
      #{same_record_lookup}.order("#{query_start_column} DESC").first
    end

    def previous
      effective_at(#{start_column} - 1.day)
    end

    def next
      effective_at(#{end_column} + 1.day)
    end

    def current
      effective_at(Time.now)
    end

    def current?
      (#{start_column}.blank? || #{start_column}.to_time <= Time.now) && (#{end_column}.blank? || #{end_column}.to_time >= Time.now)
    end
EOS
end