Class: ActiveModel::Validations::BarcodeValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_model/validations/barcode_validator.rb

Instance Method Summary collapse

Instance Method Details

#valid_ean13?(value) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
# File 'lib/active_model/validations/barcode_validator.rb', line 12

def valid_ean13?(value)
  if value =~ /^\d{13}$/
    ean13_check_digit(value.slice(0,12)) == value.slice(12)
  end
end

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/active_model/validations/barcode_validator.rb', line 4

def validate_each(record, attribute, value)
  # EAN13 by default
  format = options.fetch(:format, :ean13)  
  method = "valid_#{format.to_s}?"
  raise "Barcode format not supported (#{format})" unless self.respond_to?(method)
  record.errors.add(attribute) if value.blank? || !self.send(method, value)
end