Guest User

Untitled

a guest
Feb 19th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. class CreditCard < ActiveRecord::Base
  2. belongs_to :legal_entity
  3. validates_numericality_of :number, :only_integer => true
  4. validates_presence_of :number, :expiration_date, :card_type
  5. validates_uniqueness_of :number, :scope => 'account_id', :message => 'matches a credit card already on your account'
  6. belongs_to :account
  7.  
  8. def validate
  9. errors.add("number", "is not a #{card_type} or is invalid") unless number_valid? && number_matches_type?
  10. end
  11.  
  12. def self.card_types
  13. { 'Visa' => 'visa',
  14. 'MasterCard' => 'mastercard',
  15. 'Discover' => 'discover',
  16. 'American Express' => 'amex' }
  17. end
  18.  
  19. def readable_card_type
  20. (@@card_types ||= self.class.card_types.invert)[card_type]
  21. end
  22.  
  23. def digits
  24. @digits ||= number.gsub(/[^0-9]/, '')
  25. end
  26.  
  27. def last_digits
  28. digits.sub(/^([0-9]+)([0-9]{4})$/) { '*' * $1.length + $2 }
  29. end
  30.  
  31. protected
  32. def number_valid?
  33. total = 0
  34. digits.reverse.scan(/(\d)(\d){0,1}/) do |ud,ad|
  35. (ad.to_i*2).to_s.each {|d| total = total + d.to_i} if ad
  36. total = total + ud.to_i
  37. end
  38. total % 10 != 0
  39. end
  40.  
  41. def number_matches_type?
  42. digit_length = digits.length
  43. case card_type
  44. when 'visa'
  45. [13,16].include?(digit_length) and number[0,1] == "4"
  46. when 'mastercard'
  47. digit_length == 16 and ("51" .. "55").include?(number[0,2])
  48. when 'amex'
  49. digit_length == 15 and %w(34 37).include?(number[0,2])
  50. when 'discover'
  51. digit_length == 16 and number[0,4] == "6011"
  52. end
  53. end
  54. end
Add Comment
Please, Sign In to add comment