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

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

  # format check
  date_regexp_holders

  if !@options[:from].nil? && !@options[:from].is_a?(Date)
    date = parse_date(@options[:from].to_s)
    if date.nil?
      raise ArgumentError.new("Invalid date expression '#{@options[:from]}'")
    else
      @options[:from] = date
    end
  end

  if !@options[:to].nil? && !@options[:to].is_a?(Date)
    date = parse_date(@options[:to].to_s)
    if date.nil?
      raise ArgumentError.new("Invalid date expression '#{@options[:to]}'")
    else
      @options[:to] = date
    end
  end
end

Instance Method Details

#formatObject



79
80
81
# File 'lib/anodator/validator/date_validator.rb', line 79

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

#fromObject



63
64
65
66
67
68
69
# File 'lib/anodator/validator/date_validator.rb', line 63

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

#toObject



71
72
73
74
75
76
77
# File 'lib/anodator/validator/date_validator.rb', line 71

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

#validateObject



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

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 configuration > date
      when :to
        return false if configuration < date
      end
    end

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