Class: GuardrailsRuby::Checks::KeywordFilter

Inherits:
GuardrailsRuby::Check show all
Defined in:
lib/guardrails_ruby/checks/keyword_filter.rb

Instance Attribute Summary

Attributes inherited from GuardrailsRuby::Check

#options

Instance Method Summary collapse

Methods inherited from GuardrailsRuby::Check

check_name, direction, #initialize, lookup

Constructor Details

This class inherits a constructor from GuardrailsRuby::Check

Instance Method Details

#call(text, context: {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/guardrails_ruby/checks/keyword_filter.rb', line 9

def call(text, context: {})
  blocklist = @options.fetch(:blocklist, [])
  allowlist = @options.fetch(:allowlist, [])

  text_lower = text.downcase

  if blocklist.any?
    found = blocklist.select { |kw| text_lower.include?(kw.downcase) }
    if found.any?
      return fail!("Blocked keywords found: #{found.join(', ')}", matches: found)
    end
  end

  if allowlist.any?
    has_allowed = allowlist.any? { |kw| text_lower.include?(kw.downcase) }
    unless has_allowed
      return fail!("No allowed keywords found. Expected one of: #{allowlist.join(', ')}")
    end
  end

  pass!
end