Class: CreditCardValidations::Factory

Inherits:
Object
  • Object
show all
Defined in:
lib/credit_card_validations/factory.rb

Class Method Summary collapse

Class Method Details

.generate(rule) ⇒ Object



22
23
24
# File 'lib/credit_card_validations/factory.rb', line 22

def generate(rule)
  number(rule[:prefixes].sample, rule[:length].sample, rule.fetch(:options, {})[:skip_luhn])
end

.last_digit(number) ⇒ Object

extracted from darkcoding-credit-card



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/credit_card_validations/factory.rb', line 42

def last_digit(number)
  # Calculate sum
  sum, pos = 0, 0
  length = number.length + 1

  reversed_number = number.reverse
  while pos < length do
    odd = reversed_number[pos].to_i * 2
    odd -= 9 if odd > 9

    sum += odd

    sum += reversed_number[pos + 1].to_i if pos != (length - 2)

    pos += 2
  end

  (((sum / 10).floor + 1) * 10 - sum) % 10
end

.number(prefix, length, skip_luhn = false) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/credit_card_validations/factory.rb', line 26

def number(prefix, length, skip_luhn = false)
  number = prefix.dup
  1.upto(length - (prefix.length + 1)) do
    number << "#{rand(9)}"
  end
  #if skip luhn
  if skip_luhn
    number += "#{rand(9)}"
  else
    number += last_digit(number).to_s
  end
  number
end

.random(brand = nil) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/credit_card_validations/factory.rb', line 14

def random(brand = nil)
  brand = Detector.brands.keys.sample if brand.nil?
  if Detector.brands[brand].nil?
    raise Error.new('Unsupported brand')
  end
  generate(Detector.brands[brand][:rules].sample)
end