Class: BlacklistValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- BlacklistValidator
- Defined in:
- lib/calagator/blacklist_validator.rb
Overview
BlacklistValidator
A naively simple mixin that blacklists content 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/blacklist.txt file with a line like:
\bviagrab\b
And then you’d include the blacklisting feature into your Message class like:
class Message < ActiveRecord::Base
validates :title, :content, blacklist: 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.
* blacklist: Reads an array of blacklisted regular expressions from
a filename.
* message: Error message to use on invalid records.
If no :patterns or :blacklist is given, patterns are read from:
* config/blacklist.txt
* config/blacklist-local.txt
Constant Summary collapse
- BLACKLIST_DEFAULT_MESSAGE =
"contains blacklisted content"
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
40 41 42 43 44 |
# File 'lib/calagator/blacklist_validator.rb', line 40 def validate_each(record, attribute, value) if value.present? && patterns.any? { |pattern| value.match(pattern) } record.errors.add attribute, end end |