Class: Europeana::FeedbackButton::WordCountValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/europeana/feedback_button/word_count_validator.rb

Instance Method Summary collapse

Instance Method Details

#count_words(value) ⇒ Object



21
22
23
# File 'app/validators/europeana/feedback_button/word_count_validator.rb', line 21

def count_words(value)
  value&.strip&.scan(/\w+/)&.size || 0
end

#validate_each(record, attribute, value) ⇒ Object



6
7
8
9
10
11
12
# File 'app/validators/europeana/feedback_button/word_count_validator.rb', line 6

def validate_each(record, attribute, value)
  return if options[:allow_nil] && value.nil?
  return if options[:allow_blank] && value.blank?

  minimum = options[:minimum] || 5
  validate_minimum_words(record, attribute, value, minimum)
end

#validate_minimum_words(record, attribute, value, minimum) ⇒ Object



14
15
16
17
18
19
# File 'app/validators/europeana/feedback_button/word_count_validator.rb', line 14

def validate_minimum_words(record, attribute, value, minimum)
  word_count = count_words(value)
  unless word_count >= minimum
    record.errors[attribute] << (options[:message] || "has too few words (#{word_count} < #{minimum})")
  end
end