Created
November 13, 2012 21:40
-
-
Save cknoxrun/4068581 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def check_cas_number | |
| # Check the CAS number for validity (the last number in a CAS number is a checksum) | |
| if cas_number.present? | |
| matches = cas_number.scan(/^(\d{1,7})-(\d{1,2})-(\d)$/) | |
| if matches.first.blank? || matches.first.size != 3 | |
| self.errors.add(:cas_number, "format invalid") | |
| else | |
| match = matches.first | |
| toadd = match[0].to_s + match[1].to_s | |
| check = match[2].to_s | |
| sum = 0 | |
| count = toadd.length | |
| digits = toadd.scan(/(\d)/) | |
| while(digit = digits.shift) do | |
| sum = sum + digit[0].to_i * count | |
| count = count - 1 | |
| end | |
| self.errors.add(:cas_number, "format invalid") unless check.to_i == (sum % 10).to_i | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment