Module: StringMagic::Advanced::Security
- Included in:
- String, StringMagic
- Defined in:
- lib/string_magic/advanced/security.rb
Instance Method Summary collapse
- #contains_sensitive_data? ⇒ Boolean
-
#mask_credit_cards(mask_char: '*', preserve_count: 4) ⇒ Object
Convenience wrappers.
- #mask_emails(mask_char: '*') ⇒ Object
- #mask_phones(mask_char: '*', preserve_count: 4) ⇒ Object
-
#mask_sensitive_data(options = {}) ⇒ Object
Detects and masks sensitive data in the string.
Instance Method Details
#contains_sensitive_data? ⇒ Boolean
60 61 62 63 64 65 66 67 68 |
# File 'lib/string_magic/advanced/security.rb', line 60 def contains_sensitive_data? return false if empty? [ /\b(?:\d{4}[-\s]?){3}\d{4}\b/, # Credit card /\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/, # SSN /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/ # Email ].any? { |re| match?(re) } end |
#mask_credit_cards(mask_char: '*', preserve_count: 4) ⇒ Object
Convenience wrappers
48 49 50 |
# File 'lib/string_magic/advanced/security.rb', line 48 def mask_credit_cards(mask_char: '*', preserve_count: 4) mask_sensitive_data(types: [:credit_card], mask_char: mask_char, preserve_count: preserve_count) end |
#mask_emails(mask_char: '*') ⇒ Object
52 53 54 |
# File 'lib/string_magic/advanced/security.rb', line 52 def mask_emails(mask_char: '*') mask_sensitive_data(types: [:email], mask_char: mask_char) end |
#mask_phones(mask_char: '*', preserve_count: 4) ⇒ Object
56 57 58 |
# File 'lib/string_magic/advanced/security.rb', line 56 def mask_phones(mask_char: '*', preserve_count: 4) mask_sensitive_data(types: [:phone], mask_char: mask_char, preserve_count: preserve_count) end |
#mask_sensitive_data(options = {}) ⇒ Object
Detects and masks sensitive data in the string.
options:
:mask_char
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/string_magic/advanced/security.rb', line 17 def mask_sensitive_data( = {}) return '' if empty? mask_char = .fetch(:mask_char, '*') preserve_count = .fetch(:preserve_count, 4) types = .fetch(:types, i[credit_card ssn email phone]) patterns = { credit_card: /\b(?:\d{4}[-\s]?){3}\d{4}\b/, ssn: /\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/, email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/, phone: /(?:\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}(?!\d)/ } result = dup types.each do |type| next unless patterns[type] result.gsub!(patterns[type]) do |match| case type when :credit_card then mask_credit_card(match, mask_char, preserve_count) when :ssn then mask_ssn(match, mask_char, preserve_count) when :email then mask_email(match, mask_char) when :phone then mask_phone(match, mask_char, preserve_count) end end end result end |