Class: Anodator::Validator::DateValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/anodator/validator/date_validator.rb

Constant Summary collapse

FORMAT_SCANNER_REGEXP =
/((YY(?:YY)?)|(M(?![YMD]))|(MM)|(D(?![YMD]))|(DD))/

Instance Attribute Summary

Attributes inherited from Base

#options, #target

Instance Method Summary collapse

Methods inherited from Base

#allow_blank?, #argument_value_at, default_options, #description, #target_value, #to_s, #valid?, valid_option_keys, #validate_configuration, values, values=

Constructor Details

#initialize(target_expression, options = { }) ⇒ DateValidator

Returns a new instance of DateValidator.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/anodator/validator/date_validator.rb', line 12

def initialize(target_expression, options = { })
  super(target_expression, options)

  # format check
  date_regexp_holders

  [:from, :to].each do |key|
    if !@options[key].nil?
      @options[key] = proxy_value(@options[key])
      if @options[key].direct? && !@options[key].value.is_a?(Date)
        date = parse_date(@options[key].value.to_s)
        if date.nil?
          raise ArgumentError.new("Invalid date expression '#{@options[key].value}'")
        else
          @options[key] = proxy_value(date)
        end
      end
    end
  end
end

Instance Method Details

#formatObject



75
76
77
# File 'lib/anodator/validator/date_validator.rb', line 75

def format
  return @options[:format].dup
end

#fromObject



59
60
61
62
63
64
65
# File 'lib/anodator/validator/date_validator.rb', line 59

def from
  if @options[:from]
    return @options[:from].dup
  else
    return nil
  end
end

#toObject



67
68
69
70
71
72
73
# File 'lib/anodator/validator/date_validator.rb', line 67

def to
  if @options[:to]
    return @options[:to].dup
  else
    return nil
  end
end

#validateObject



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
# File 'lib/anodator/validator/date_validator.rb', line 33

def validate
  if allow_blank?
    return true if target_value.split(//).size.zero?
  end


  begin
    # check format
    return false unless date = parse_date(target_value)

    @options.each do |option, configuration|
      case option
      when :from
        return false if parse_date(configuration.value) > date
      when :to
        return false if parse_date(configuration.value) < date
      end
    end

    return true
  rescue ArgumentError
    # invalid date expression
    return false
  end
end