2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-01-09 03:48:10 -05:00
|
|
|
class CensoredWordsValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
2023-11-01 10:41:10 -04:00
|
|
|
words_regexps = WordWatcher.compiled_regexps_for_action(:censor)
|
|
|
|
if WordWatcher.words_for_action_exist?(:censor).present? && words_regexps.present?
|
2022-08-02 04:06:03 -04:00
|
|
|
censored_words = censor_words(value, words_regexps)
|
2019-11-20 05:05:06 -05:00
|
|
|
return if censored_words.blank?
|
2022-08-02 04:06:03 -04:00
|
|
|
|
2017-01-09 03:48:10 -05:00
|
|
|
record.errors.add(
|
2019-11-20 05:05:06 -05:00
|
|
|
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
|
|
|
|
|
2022-08-02 04:06:03 -04:00
|
|
|
def censor_words(value, regexps)
|
|
|
|
censored_words = regexps.map { |r| value.scan(r) }
|
2017-04-10 17:38:48 -04:00
|
|
|
censored_words.flatten!
|
|
|
|
censored_words.compact!
|
|
|
|
censored_words.map!(&:strip)
|
|
|
|
censored_words.select!(&:present?)
|
|
|
|
censored_words.uniq!
|
|
|
|
censored_words
|
|
|
|
end
|
|
|
|
|
2017-01-24 00:11:05 -05:00
|
|
|
def join_censored_words(censored_words)
|
|
|
|
censored_words.map!(&:downcase)
|
|
|
|
censored_words.uniq!
|
2020-04-30 02:48:34 -04:00
|
|
|
censored_words.join(", ")
|
2017-01-16 00:24:47 -05:00
|
|
|
end
|
2017-01-09 03:48:10 -05:00
|
|
|
end
|