mlins (owner)

Revisions

gist: 106990 Download_button fork
public
Public Clone URL: git://gist.github.com/106990.git
Embed All Files: show embed
date_validator.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
module DateValidations
  def self.included(base) # :nodoc:
    base.extend ClassMethods
  end
 
  module ClassMethods
 
    # Must pass a Proc object with a Range of Date, Time or DateTime.
    # The Proc prevents the range from only being evaluated at initialization.
    # All 'dates' are converted to Time objects for comparison sake.
    def validates_date_range_of(*attr_names)
      configuration = parse_configuration(attr_names)
      check_for_valid_proc(configuration)
      range = get_range(configuration)
 
      validates_each(attr_names, configuration) do |record, attr_name, value|
        if value.nil? || !range.include?(value.to_date)
          record.errors.add(attr_name, error_message(configuration, range))
        end
      end
    end
 
    protected
    def parse_configuration(attr_names)
      configuration = { :on => :save, :in => nil }
      configuration.update(attr_names.extract_options!)
      configuration
    end
 
    def check_for_valid_proc(configuration)
      unless configuration[:in].is_a?(Proc)
        raise(ArgumentError, "A Proc must be supplied as the :in option of the configuration hash")
      end
      unless configuration[:in].call.is_a?(Range)
        raise(ArgumentError, "A Range must be returned from Proc.call of the :in option")
      end
    end
 
    def get_range(configuration)
      range = configuration[:in].call
      [range.first, range.last].each do |date|
        check_for_valid_range_date(date)
      end
      range.first.to_date..range.last.to_date
    end
 
    def check_for_valid_range_date(date)
      [Date, DateTime, Time].each do |klass|
        return if date.is_a?(klass)
      end
      raise(ArgumentError, "A Date, Time or DateTime object must be used to specify the Range.")
    end
 
    def error_message(configuration, range)
      message = configuration[:message]
      message ||= "must be between #{range.first.strftime("%m/%d/%Y")} " +
          "and #{range.last.strftime("%m/%d/%Y")}"
    end
  end
end