Skip to content

Instantly share code, notes, and snippets.

@schovi
Created February 5, 2011 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schovi/812447 to your computer and use it in GitHub Desktop.
Save schovi/812447 to your computer and use it in GitHub Desktop.
This peace of code provide validation of isbn (lenght, format, sum of number).
class Book < ActiveRecord::Base
attr_accessor :isbn
validate :format_of_isbn
private
def format_of_isbn
normalized_isbn = self.isbn.to_s.gsub(/_|-/, '')
if normalized_isbn.length == 10
unless normalized_isbn =~ /\d{9}(\d{1}|x)/i
errors.add(:isbn, I18n.t('isbn_validation.wrong_format'))
return false
end
numbers = normalized_isbn.split('').collect {|s| s =~ /x/i ? 10 : s.to_i }
result = (1..10).to_a.reverse.zip(numbers).collect {|a| a.reduce(&:*)}.reduce(&:+)
if (result % 11) == 0
return true
else
errors.add(:isbn, I18n.t('isbn_validation.invalid_number'))
return false
end
elsif normalized_isbn.length == 13
unless normalized_isbn =~ /\d{13}/i
errors.add(:isbn, I18n.t('isbn_validation.wrong_format'))
return false
end
numbers = normalized_isbn.split('').collect(&:to_i)
result = ([1,3] * 7)[0..-2].zip(numbers).collect {|a| a.reduce(&:*)}.reduce(&:+)
if (result % 10) == 0
return true
else
errors.add(:isbn, I18n.t('isbn_validation.invalid_number'))
return false
end
else
errors.add(:isbn, I18n.t('isbn_validation.wrong_length'))
return false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment