Class: ValidCreditCard::CreditCard

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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

#numberObject

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_typeObject



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

Returns:

  • (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

Returns:

  • (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_luhnObject



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