Class: FullMetalBody::Internal::InputStringValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/full_metal_body/internal/input_string_validator.rb

Constant Summary collapse

DEFAULT_MAX_LENGTH =
1024

Instance Method Summary collapse

Instance Method Details

#byteslice(value) ⇒ Object



54
55
56
# File 'lib/full_metal_body/internal/input_string_validator.rb', line 54

def byteslice(value)
  value.byteslice(0, 1024)
end

#check_validity!Object



8
9
10
11
12
13
# File 'lib/full_metal_body/internal/input_string_validator.rb', line 8

def check_validity!
  if options[:max_length]
    value = options[:max_length]
    raise ArgumentError, ":max_length must be a non-negative Integer" unless value.is_a?(Integer) && value >= 0
  end
end

#validate_each(record, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/full_metal_body/internal/input_string_validator.rb', line 15

def validate_each(record, attribute, value)
  return if value.nil?

  if value.is_a?(Array)
    value.each do |v|
      validate_value(record, attribute, v.dup)
    end
  else
    validate_value(record, attribute, value.dup)
  end
end

#validate_value(record, attribute, value) ⇒ Object



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
# File 'lib/full_metal_body/internal/input_string_validator.rb', line 27

def validate_value(record, attribute, value)
  max_length = options[:max_length] || DEFAULT_MAX_LENGTH

  # type
  unless value.is_a? String
    return record.errors.add(attribute, :wrong_type, value: value)
  end

  # length
  if value.size > max_length
    return record.errors.add(attribute, :too_long, value: byteslice(value), count: value.size)
  end

  # encoding
  original_encoding = value.encoding.name
  unless value.force_encoding('UTF-8').valid_encoding?
    return record.errors.add(attribute, :wrong_encoding, value: byteslice(value), encoding: original_encoding)
  end

  # cntrl
  # Replace and delete line feed codes and horizontal tabs (vertical tabs are not)
  value = value.gsub(/\R|\t/, '')
  if /[[:cntrl:]]/.match?(value)
    record.errors.add(attribute, :include_cntrl, value: byteslice(value))
  end
end