Class: PottyMouthValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- PottyMouthValidator
- Defined in:
- lib/validates_potty_mouth/potty_mouth_validator.rb
Overview
this is not namespaced so that we can do
validates :body, potty_mouth: true
Class Method Summary collapse
Instance Method Summary collapse
- #banned?(value) ⇒ Boolean
- #banned_word?(word) ⇒ Boolean
- #banned_word_list ⇒ Object
- #validate_each(record, attribute, value) ⇒ Object
Class Method Details
.add_word_list(type, path) ⇒ Object
35 36 37 |
# File 'lib/validates_potty_mouth/potty_mouth_validator.rb', line 35 def add_word_list(type, path) banned_word_lists[type.to_sym] = File.read(path).split("\n").map{|word| word.chomp.downcase}.to_set end |
.banned_word_lists ⇒ Object
31 32 33 |
# File 'lib/validates_potty_mouth/potty_mouth_validator.rb', line 31 def banned_word_lists @lists ||= Hash.new { Set.new } end |
Instance Method Details
#banned?(value) ⇒ Boolean
14 15 16 17 18 |
# File 'lib/validates_potty_mouth/potty_mouth_validator.rb', line 14 def banned?(value) text = value.gsub(/[\W\d]/, ' ') # get rid of non-letters words = text.split.to_set words.any?{|word| banned_word?(word)} end |
#banned_word?(word) ⇒ Boolean
20 21 22 23 24 |
# File 'lib/validates_potty_mouth/potty_mouth_validator.rb', line 20 def banned_word?(word) down_word = word.downcase banned_word_list.include?(down_word) || banned_word_list.include?(down_word.stem) end |
#banned_word_list ⇒ Object
26 27 28 |
# File 'lib/validates_potty_mouth/potty_mouth_validator.rb', line 26 def banned_word_list self.class.banned_word_lists[.fetch(:list, :default)] end |
#validate_each(record, attribute, value) ⇒ Object
6 7 8 9 10 11 12 |
# File 'lib/validates_potty_mouth/potty_mouth_validator.rb', line 6 def validate_each(record, attribute, value) return true if value.blank? if banned?(value) record.errors[attribute] << .fetch(:message, "contains objectionable content") end end |