Further refactor SiretFormatValidator#validate_each

This commit is contained in:
gregoirenovel 2018-09-19 10:28:07 +02:00
parent 36950b985b
commit 940dfe422b

View file

@ -1,16 +1,24 @@
class SiretFormatValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if !value&.match?(/^\d{14}$/)
if !format_is_valid(value)
record.errors.add(attribute, :format)
end
if value.present? && (luhn_checksum(value) % 10 != 0)
if !luhn_passed(value)
record.errors.add(attribute, :checksum)
end
end
private
def format_is_valid(value)
value&.match?(/^\d{14}$/)
end
def luhn_passed(value)
value.present? && (luhn_checksum(value) % 10 == 0)
end
def luhn_checksum(value)
accum = 0