Class: ValidationExtensions::IsbnValidation::IsbnFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/isbn_validation.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ IsbnFormatValidator

Returns a new instance of IsbnFormatValidator.



32
33
34
35
36
37
# File 'lib/isbn_validation.rb', line 32

def initialize(options)
  options[:message]     ||= "is not a valid ISBN code"
  options[:allow_nil]   ||= false
  options[:allow_blank] ||= false
  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/isbn_validation.rb', line 39

def validate_each(record, attribute, value)
  valid_isbn = case options[:with]
               when :isbn10
                 validate_with_isbn10(value)
               when :isbn13
                 validate_with_isbn13(value)
               else
                 validate_with_isbn10(value) || validate_with_isbn13(value)
               end

  unless valid_isbn || (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
    record.errors.add(attribute, options[:message])
  end
end