Improve SiretFormatValidator readability
This commit is contained in:
parent
471f6799c8
commit
49d872452a
1 changed files with 4 additions and 1 deletions
|
@ -1,8 +1,9 @@
|
||||||
class SiretFormatValidator < ActiveModel::EachValidator
|
class SiretFormatValidator < ActiveModel::EachValidator
|
||||||
def validate_each(record,attribute,value)
|
def validate_each(record, attribute, value)
|
||||||
if !(value =~ /^\d{14}$/)
|
if !(value =~ /^\d{14}$/)
|
||||||
record.errors.add(attribute, :format)
|
record.errors.add(attribute, :format)
|
||||||
end
|
end
|
||||||
|
|
||||||
if value.nil? || (luhn_checksum(value) % 10 != 0)
|
if value.nil? || (luhn_checksum(value) % 10 != 0)
|
||||||
record.errors.add(attribute, :checksum)
|
record.errors.add(attribute, :checksum)
|
||||||
end
|
end
|
||||||
|
@ -12,11 +13,13 @@ class SiretFormatValidator < ActiveModel::EachValidator
|
||||||
|
|
||||||
def luhn_checksum(value)
|
def luhn_checksum(value)
|
||||||
accum = 0
|
accum = 0
|
||||||
|
|
||||||
value.reverse.each_char.map(&:to_i).each_with_index do |digit, index|
|
value.reverse.each_char.map(&:to_i).each_with_index do |digit, index|
|
||||||
t = index.even? ? digit : digit * 2
|
t = index.even? ? digit : digit * 2
|
||||||
t = t - 9 if t >= 10
|
t = t - 9 if t >= 10
|
||||||
accum += t
|
accum += t
|
||||||
end
|
end
|
||||||
|
|
||||||
accum
|
accum
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue