Class: GuardrailsRuby::Redactors::KeywordRedactor
- Inherits:
-
Object
- Object
- GuardrailsRuby::Redactors::KeywordRedactor
- Defined in:
- lib/guardrails_ruby/redactors/keyword_redactor.rb
Instance Method Summary collapse
-
#detect(text) ⇒ Object
Detect which keywords are present in text.
-
#initialize(keywords, replacement: "[REDACTED]") ⇒ KeywordRedactor
constructor
Initialize with a list of keywords to redact.
-
#redact(text) ⇒ Object
Redact all occurrences of the configured keywords from text (case-insensitive).
Constructor Details
#initialize(keywords, replacement: "[REDACTED]") ⇒ KeywordRedactor
Initialize with a list of keywords to redact.
redactor = KeywordRedactor.new(%w[secret password], replacement: "[HIDDEN]")
redactor.redact("The secret password is abc123")
# => "The [HIDDEN] [HIDDEN] is abc123"
12 13 14 15 |
# File 'lib/guardrails_ruby/redactors/keyword_redactor.rb', line 12 def initialize(keywords, replacement: "[REDACTED]") @keywords = keywords @replacement = replacement end |
Instance Method Details
#detect(text) ⇒ Object
Detect which keywords are present in text. Returns an array of matched keywords.
28 29 30 |
# File 'lib/guardrails_ruby/redactors/keyword_redactor.rb', line 28 def detect(text) @keywords.select { |kw| text.match?(/\b#{Regexp.escape(kw)}\b/i) } end |
#redact(text) ⇒ Object
Redact all occurrences of the configured keywords from text (case-insensitive). Uses word boundary matching to avoid partial-word replacements.
19 20 21 22 23 24 25 |
# File 'lib/guardrails_ruby/redactors/keyword_redactor.rb', line 19 def redact(text) result = text.dup @keywords.each do |kw| result.gsub!(/\b#{Regexp.escape(kw)}\b/i, @replacement) end result end |