Class: ActiveModel::Validations::BarcodeValidator

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

Instance Method Summary collapse

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


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

def check_validity!
  format = options.fetch(:format)
  raise ArgumentError, ":format cannot be blank!" if format.blank?
  method = "valid_#{format.to_s}?"
  raise ArgumentError, "Barcode format (#{format}) not supported" unless self.respond_to?(method)
end

#valid_ean13?(value) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
# File 'lib/active_validators/active_model/validations/barcode_validator.rb', line 18

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



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

def validate_each(record, attribute, value)
  method = "valid_#{options[:format].to_s}?"
  record.errors.add(attribute) if value.blank? || !self.send(method, value.to_s)
end