class Maskerade::CreditCardMasker

Constants

ALL_CARDS_REGEX
COMPANY_CARD_REGEX
DIGIT_REGEX

Attributes

expose_last[R]
replacement_token[R]

Public Class Methods

new(replacement_text: nil, replacement_token: "X", expose_last: 0) click to toggle source

Options:

replacement_text: The entire card number gets replaced with this text; if set, the other two options are ignored.
replacement_token: The character used to replace digits of the credit number.  Defaults to "X".
expose_last: The number of trailing digits of the credit card number to leave intact.  Defaults to 0.
# File lib/maskerade/credit_card_masker.rb, line 33
def initialize(replacement_text: nil, replacement_token: "X", expose_last: 0)
  @replacement_text = replacement_text
  @replacement_token = replacement_token
  @expose_last = expose_last
end

Public Instance Methods

mask(value) click to toggle source
# File lib/maskerade/credit_card_masker.rb, line 39
def mask(value)
  value&.gsub(ALL_CARDS_REGEX) do |match|
    mask_one(match)
  end
end

Private Instance Methods

mask_one(value) click to toggle source
# File lib/maskerade/credit_card_masker.rb, line 47
def mask_one(value)
  digits = value.tr("^0-9", "")
  return value unless ::LuhnChecksum.valid?(digits)

  return @replacement_text if @replacement_text

  value.gsub(DIGIT_REGEX).with_index do |number, index|
    if index < digits.size - expose_last
      replacement_token
    else
      number
    end
  end
end