From: Jeffrey Moss Date: 2005-03-24T08:22:45+09:00 Subject: Credit Card Verification as an exercise ------=_NextPart_000_0062_01C52FC4.7DDBCEE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Couldn't find any credit card verification code written in ruby so I = wrote up my own. This code turns out a lot smaller than the perl = version I have been using. I thought it was an interesting exercise, = here is how its done, if anybody can improve on what I've done I'd be = impressed. Heres a howto guide on it http://www.beachnet.com/~hstiles/cardtype.html Feel free to use the code. class CreditCard < ActiveRecord::Base def before_save if number_is_valid && number_matches_type ... end end def number_is_valid total =3D 0 number.gsub(/[^0-9]/, '').reverse.scan(/(\d)(\d){0,1}/) do |ud,ad| (ad.to_i*2).to_s.each {|d| total =3D total + d.to_i} if ad total =3D total + ud.to_i end total % 10 =3D=3D 0 ? false : true end def number_matches_type digit_length =3D number.length if card_type =3D=3D 'visa' if (digit_length =3D=3D 16) || (digit_length =3D=3D 13) return true if number[/^\d/].to_i =3D=3D 4 end elsif card_type =3D=3D 'mastercard' if digit_length =3D=3D 16 return true if (51..55).to_a.include?(number[0..1].to_i) end elsif card_type =3D=3D 'amex' if digit_length =3D=3D 15 return true if [34,37].include?(number[0..1].to_i) end elsif card_type =3D=3D 'discover' if digit_length =3D=3D 16 return true if number[0..3].to_i =3D=3D 6011 end end end end ------=_NextPart_000_0062_01C52FC4.7DDBCEE0--