Class: ValidCreditCard::CreditCard
- Inherits:
-
Object
- Object
- ValidCreditCard::CreditCard
- Defined in:
- lib/valid_credit_card/credit_card.rb
Constant Summary collapse
- CARD_TYPES =
{ visa: /\A4[0-9]{12}(?:[0-9]{3})?\z/, master_card: /\A5[1-5][0-9]{14}\z/, maestro: /(\A6759[0-9]{2}([0-9]{10})$)|(\A6759[0-9]{2}([0-9]{12})$)|(\A6759[0-9]{2}([0-9]{13})$)/, diners_club: /\A3(?:0[0-5]|[68][0-9])[0-9]{11}\z/, amex: /\A3[47][0-9]{13}\z/, discover: /\A6(?:011|5[0-9]{2})[0-9]{12}\z/, jcb: /\A(?:2131|1800|35\d{3})\d{11}\z/ }
Instance Attribute Summary collapse
-
#number ⇒ Object
Returns the value of attribute number.
Instance Method Summary collapse
- #card_type ⇒ Object
-
#initialize(number) ⇒ CreditCard
constructor
Initializer.
- #is_test_number? ⇒ Boolean
- #valid? ⇒ Boolean
- #verify_luhn ⇒ Object
Constructor Details
#initialize(number) ⇒ CreditCard
Initializer
18 19 20 |
# File 'lib/valid_credit_card/credit_card.rb', line 18 def initialize(number) @number = number.to_s end |
Instance Attribute Details
#number ⇒ Object
Returns the value of attribute number.
15 16 17 |
# File 'lib/valid_credit_card/credit_card.rb', line 15 def number @number end |
Instance Method Details
#card_type ⇒ Object
26 27 28 |
# File 'lib/valid_credit_card/credit_card.rb', line 26 def card_type CARD_TYPES.select{ |k, v| (strip_number =~ v).present? }.keys[0].to_s end |
#is_test_number? ⇒ Boolean
30 31 32 |
# File 'lib/valid_credit_card/credit_card.rb', line 30 def is_test_number? ValidCreditCard.test_numbers.include?(strip_number) end |
#valid? ⇒ Boolean
22 23 24 |
# File 'lib/valid_credit_card/credit_card.rb', line 22 def valid? (verify_luhn && strip_number.length >= 11 && card_type.present?) || is_test_number? end |
#verify_luhn ⇒ Object
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/valid_credit_card/credit_card.rb', line 34 def verify_luhn total = strip_number.reverse().split(//).inject([0,0]) do |accum, n| n = n.to_i accum[0] += (accum[1] % 2 == 1 ? rotate(n * 2) : n) accum[1] += 1 accum end (total[0] % 10 == 0) end |