Class: DenylistValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- DenylistValidator
- Defined in:
- lib/calagator/denylist_validator.rb
Overview
DenylistValidator
A naively simple mixin used to ban words in ActiveModel objects.
Usage
Let's say that your applications lets people post messages, but don't want them using the word “viagra” in posts as a naively simple way of preventing spam.
You'd first create a config/denylist.txt file with a line like:
\bviagrab\b
And then you'd include the denylisting feature into your Message class like:
class Message < ApplicationRecord
validates :title, :content, denylist: true
end
Now including the word “viagra” in your record's values will fail:
= Message.new(title: "foo viagra bar")
.valid? # => false
Available validator options:
* patterns: Array of regular expressions that will be matched
against the given attribute contents and any matches will cause the
record to be marked invalid.
* denylist: Reads an array of denylisted regular expressions from
a filename.
* message: Error message to use on invalid records.
If no :patterns or :denylist is given, patterns are read from:
* config/denylist.txt
* config/denylist-local.txt
Constant Summary collapse
- DENYLIST_DEFAULT_MESSAGE =
'contains denylisted content'
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
42 43 44 45 46 |
# File 'lib/calagator/denylist_validator.rb', line 42 def validate_each(record, attribute, value) if value.present? && patterns.any? { |pattern| value.match(pattern) } record.errors.add attribute, end end |