Class: Synthra::Types::FinanceBanking::CreditCard

Inherits:
Base
  • Object
show all
Defined in:
lib/synthra/types/finance_banking/banking.rb

Overview

CreditCard type

Constant Summary collapse

CARD_TYPES =

Credit card type definitions

Maps card type symbols to their specifications including valid prefixes and card number length.

Examples:

CARD_TYPES[:visa]       # => { prefix: [4], length: 16 }
CARD_TYPES[:mastercard] # => { prefix: [51, 52, 53, 54, 55], length: 16 }

Returns:

  • (Hash<Symbol, Hash>)

    card type to specification mapping

{
  visa: { prefix: [4], length: 16 },
  mastercard: { prefix: [51, 52, 53, 54, 55], length: 16 },
  amex: { prefix: [34, 37], length: 15 },
  discover: { prefix: [6011, 65], length: 16 },
  diners: { prefix: [30, 36, 38], length: 14 },
  jcb: { prefix: [35], length: 16 }
}.freeze

Instance Method Summary collapse

Instance Method Details

#calculate_luhn_check_digit(number) ⇒ Object (private)



181
182
183
184
185
186
187
188
189
190
# File 'lib/synthra/types/finance_banking/banking.rb', line 181

def calculate_luhn_check_digit(number)
  sum = 0
  number.reverse.chars.each_with_index do |digit, index|
    n = digit.to_i
    n *= 2 if index.odd?
    n -= 9 if n > 9
    sum += n
  end
  (10 - (sum % 10)) % 10
end

#generate_edge(rng, context, args) ⇒ Object



171
172
173
# File 'lib/synthra/types/finance_banking/banking.rb', line 171

def generate_edge(rng, context, args)
  ["4111111111111111", "4000000000000002"].sample(random: rng.instance_variable_get(:@random))
end

#generate_invalid(rng, context, args) ⇒ Object



175
176
177
# File 'lib/synthra/types/finance_banking/banking.rb', line 175

def generate_invalid(rng, context, args)
  rng.sample([nil, "1234", "invalid", [], {}])
end

#generate_random(rng, context, args) ⇒ String

Generate random credit card number

Parameters:

Options Hash (args):

  • :type (Symbol, String)

    card type (:visa, :mastercard, :amex, etc.)

Returns:

  • (String)

    generated credit card number



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/synthra/types/finance_banking/banking.rb', line 147

def generate_random(rng, context, args)
  type = (args[:type] || rng.sample(CARD_TYPES.keys)).to_sym
  card_spec = CARD_TYPES[type] || CARD_TYPES[:visa]

  # :nocov:
  # The non-Array arm is unreachable: every CARD_TYPES entry (and the
  # :visa default) declares an Array prefix, so card_spec[:prefix] is
  # always an Array here.
  prefix = card_spec[:prefix].is_a?(Array) ? rng.sample(card_spec[:prefix]) : card_spec[:prefix]
  # :nocov:
  length = card_spec[:length]

  # Generate base number with prefix
  base = prefix.to_s
  remaining = length - base.length - 1 # -1 for check digit

  # Fill with random digits
  remaining.times { base += rng.int(0, 9).to_s }

  # Calculate and append Luhn check digit
  check_digit = calculate_luhn_check_digit(base)
  "#{base}#{check_digit}"
end