Class: GlobalCollect::FieldValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/global_collect/field_validator.rb

Overview

WDL §5 TABLE 10 specifies the tokens and their meaning

Instance Method Summary collapse

Constructor Details

#initialize(token, required) ⇒ FieldValidator

Returns a new instance of FieldValidator.



4
5
6
7
8
9
10
11
12
# File 'lib/global_collect/field_validator.rb', line 4

def initialize(token, required)
  if token =~ /([A-Z]{1,2})(\d+)?/
    @type = $1
    @size = $2.to_i
    @required = (required == "R")
  else
    raise ArgumentError.new("Invalid validation token '#{token}'!")
  end
end

Instance Method Details

#inspectObject



22
23
24
# File 'lib/global_collect/field_validator.rb', line 22

def inspect
  "<FieldValidator #{to_sym}[#{@size}]>"
end

#to_symObject



14
15
16
17
18
19
20
# File 'lib/global_collect/field_validator.rb', line 14

def to_sym
  case @type
  when "D"  then :datetime
  when "AN" then :alphanumeric
  when "N"  then :numeric
  end
end

#validate(value) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/global_collect/field_validator.rb', line 26

def validate(value)
  return false if  @required && value.nil?
  return true  if !@required && value.nil?
  value = value.to_s
  case @type
  # Examples throughout §5 suggest this date format.
  # See §5.1.3. Example for instance.
  when "D"
    size = @size.zero? ? 14 : @size
    return !!(value =~ /^\d{#{size}}$/) && (!!Time.parse(value) rescue false)
  # This is a liberal interpretation of alphanumeric, but examples like
  # §5.3.1 (IPADDRESS), §5.28.1 (CITY) suggest that spaces and punctuation
  # are acceptable as well. This leaves us just checking max size.
  when "AN"
    return !!(value =~ /^.{0,#{@size}}$/)
  # §5.28.1 (AMOUNT) seems to allow for size <= the specifier.
  when "N"
    return !!(value =~ /^\d{1,#{@size}}$/)
  end
end