2017-01-09 03:48:10 -05:00
|
|
|
class CensoredWordsValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
2017-06-28 16:56:44 -04:00
|
|
|
if WordWatcher.words_for_action(:censor).present? && (censored_words = censor_words(value, censored_words_regexp)).present?
|
2017-01-09 03:48:10 -05:00
|
|
|
record.errors.add(
|
|
|
|
attribute, :contains_censored_words,
|
2017-01-24 00:11:05 -05:00
|
|
|
censored_words: join_censored_words(censored_words)
|
2017-01-09 03:48:10 -05:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
2017-01-24 00:11:05 -05:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-06-07 01:28:18 -04:00
|
|
|
def censor_words(value, regexp)
|
|
|
|
censored_words = value.scan(regexp)
|
|
|
|
censored_words.flatten!
|
|
|
|
censored_words.compact!
|
|
|
|
censored_words.map!(&:strip)
|
|
|
|
censored_words.select!(&:present?)
|
|
|
|
censored_words.uniq!
|
|
|
|
censored_words
|
|
|
|
end
|
2017-04-10 17:38:48 -04:00
|
|
|
|
2018-06-07 01:28:18 -04:00
|
|
|
def join_censored_words(censored_words)
|
|
|
|
censored_words.map!(&:downcase)
|
|
|
|
censored_words.uniq!
|
|
|
|
censored_words.join(", ".freeze)
|
|
|
|
end
|
2017-01-16 00:24:47 -05:00
|
|
|
|
2018-06-07 01:28:18 -04:00
|
|
|
def censored_words_regexp
|
|
|
|
WordWatcher.word_matcher_regexp :censor
|
|
|
|
end
|
2017-01-09 03:48:10 -05:00
|
|
|
end
|