Module: ConcernsOnRails::Support::Masker

Defined in:
lib/concerns_on_rails/support/masker.rb

Overview

Display-only value-masking helpers shared by Models::Maskable.

Every method is string-safe: a non-String argument is returned untouched, exactly like the Normalizable / Sanitizable preset lambdas. Masking is for presentation only — callers keep the original value in the database.

Constant Summary collapse

DEFAULT_MASK =
"*".freeze

Class Method Summary collapse

Class Method Details

.all(value, mask: DEFAULT_MASK) ⇒ Object

Replace every character with the mask character.



16
17
18
# File 'lib/concerns_on_rails/support/masker.rb', line 16

def all(value, mask: DEFAULT_MASK)
  value.is_a?(String) ? mask * value.length : value
end

.credit_card(value, mask: DEFAULT_MASK) ⇒ Object

Keep the last four digits of a card number: “**** **** **** 4242”.



50
51
52
53
54
55
56
57
# File 'lib/concerns_on_rails/support/masker.rb', line 50

def credit_card(value, mask: DEFAULT_MASK)
  return value unless value.is_a?(String)

  digits = value.gsub(/\D/, "")
  return all(value, mask: mask) if digits.length <= 4

  "#{mask * 4} #{mask * 4} #{mask * 4} #{digits[-4..]}"
end

.email(value, mask: DEFAULT_MASK) ⇒ Object

Mask the local part of an email, keeping the first character + domain:

"john.doe@example.com" => "j*******@example.com"


29
30
31
32
33
34
35
36
37
# File 'lib/concerns_on_rails/support/masker.rb', line 29

def email(value, mask: DEFAULT_MASK)
  return value unless value.is_a?(String)

  local, at, domain = value.partition("@")
  return value if at.empty? # not an email-shaped string; leave it alone

  masked_local = local.length <= 1 ? mask : local[0] + (mask * (local.length - 1))
  "#{masked_local}@#{domain}"
end

.last4(value, mask: DEFAULT_MASK) ⇒ Object

Keep only the last four characters visible.



21
22
23
24
25
# File 'lib/concerns_on_rails/support/masker.rb', line 21

def last4(value, mask: DEFAULT_MASK)
  return value unless value.is_a?(String)

  value.length <= 4 ? mask * value.length : (mask * (value.length - 4)) + value[-4..]
end

.phone(value, mask: DEFAULT_MASK) ⇒ Object

Keep the last four digits of a phone number visible: “***-2671”.



40
41
42
43
44
45
46
47
# File 'lib/concerns_on_rails/support/masker.rb', line 40

def phone(value, mask: DEFAULT_MASK)
  return value unless value.is_a?(String)

  digits = value.gsub(/\D/, "")
  return value if digits.empty?

  "#{mask * 3}-#{digits.length <= 4 ? digits : digits[-4..]}"
end