Class: AttrMasker::Maskers::Replacing

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_masker/maskers/replacing.rb

Overview

Replacing masker replaces every character of string which is being masked with replacement one, preserving the length of the masked string (provided that a replacement string contains a single character, which is a typical case). Optionally, non-alphanumeric characters like dashes or spaces may be left unchanged.

Examples:

Would mask “Adam West” as “XXXXXXXXX”

class User < ActiveRecord::Base
  m = AttrMasker::Maskers::Replacing.new(replacement: "X")
  attr_masker :name, :masker => m
end

Would mask “123-456-789” as “XXX-XXX-XXX”

class User < ActiveRecord::Base
  m = AttrMasker::Maskers::Replacing.new(
      replacement: "X", alphanum_only: true)
  attr_masker :phone, :masker => m
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(replacement: "*", alphanum_only: false) ⇒ Replacing

Returns a new instance of Replacing.

Parameters:

  • replacement (String) (defaults to: "*")

    replacement string

  • alphanum_only (Boolean) (defaults to: false)

    whether to leave non-alphanumeric characters unchanged or not



30
31
32
33
34
# File 'lib/attr_masker/maskers/replacing.rb', line 30

def initialize(replacement: "*", alphanum_only: false)
  replacement = "" if replacement.nil?
  @replacement = replacement
  @alphanum_only = alphanum_only
end

Instance Attribute Details

#alphanum_onlyObject (readonly)

Returns the value of attribute alphanum_only.



25
26
27
# File 'lib/attr_masker/maskers/replacing.rb', line 25

def alphanum_only
  @alphanum_only
end

#replacementObject (readonly)

Returns the value of attribute replacement.



25
26
27
# File 'lib/attr_masker/maskers/replacing.rb', line 25

def replacement
  @replacement
end

Instance Method Details

#call(value:, **_opts) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/attr_masker/maskers/replacing.rb', line 36

def call(value:, **_opts)
  return value unless value.is_a? String

  if alphanum_only
    value.gsub(/[[:alnum:]]/, replacement)
  else
    replacement * value.size
  end
end