Class: ActiveModel::Validations::EncodableValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_model/validators/encodable_validator.rb

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



6
7
8
9
10
11
# File 'lib/active_model/validators/encodable_validator.rb', line 6

def check_validity!
  values = options[:encodings]
  unless values.respond_to?(:all?) and values.all? {|v| v.class <= Encoding} 
    raise ArgumentError, ":encodings must be a array of Encodings"
  end
end

#validate_each(record, attr_name, value) ⇒ Object



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
# File 'lib/active_model/validators/encodable_validator.rb', line 13

def validate_each(record, attr_name, value)
  return if options[:allow_nil] && value.nil?

  unless value.respond_to?(:encode)
    record.errors.add(attr_name, :not_a_encodable_object , options)
    return
  end

  src_enc = value.encoding
  last_enc = nil
  begin
    options[:encodings].each do |enc|
      last_enc = enc
      value.encode(enc, src_enc)
    end
  rescue Encoding::UndefinedConversionError
    record.errors.add(attr_name, :can_not_be_encoded, options.merge(
      :value => value,
      :encoding => last_enc
    ))
    return
  rescue Encoding::InvalidByteSequenceError
    record.errors.add(attr_name, :included_invalid_byte_sequences, options)
    return
  end
end