2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-01-09 02:48:10 -06:00
|
|
|
class CensoredWordsValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
2019-11-20 04:05:06 -06:00
|
|
|
words_regexp = censored_words_regexp
|
|
|
|
if WordWatcher.words_for_action(:censor).present? && !words_regexp.nil?
|
|
|
|
censored_words = censor_words(value, words_regexp)
|
|
|
|
return if censored_words.blank?
|
2017-01-09 02:48:10 -06:00
|
|
|
record.errors.add(
|
2019-11-20 04:05:06 -06:00
|
|
|
attribute,
|
|
|
|
:contains_censored_words,
|
2017-01-23 23:11:05 -06:00
|
|
|
censored_words: join_censored_words(censored_words)
|
2017-01-09 02:48:10 -06:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
2017-01-23 23:11:05 -06:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-06-07 00:28:18 -05: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 16:38:48 -05:00
|
|
|
|
2018-06-07 00:28:18 -05:00
|
|
|
def join_censored_words(censored_words)
|
|
|
|
censored_words.map!(&:downcase)
|
|
|
|
censored_words.uniq!
|
2020-04-30 01:48:34 -05:00
|
|
|
censored_words.join(", ")
|
2018-06-07 00:28:18 -05:00
|
|
|
end
|
2017-01-15 23:24:47 -06:00
|
|
|
|
2018-06-07 00:28:18 -05:00
|
|
|
def censored_words_regexp
|
|
|
|
WordWatcher.word_matcher_regexp :censor
|
|
|
|
end
|
2017-01-09 02:48:10 -06:00
|
|
|
end
|