Sha256: d4be35406da51261a5c46e258c0e95bda22dd67f8c10b64261266a0b07dc7870

Contents?: true

Size: 787 Bytes

Versions: 2

Compression:

Stored size: 787 Bytes

Contents

# frozen_string_literal: true

module Europeana
  module FeedbackButton
    class WordCountValidator < ActiveModel::EachValidator
      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

      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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
europeana-feedback-button-0.0.7 app/validators/europeana/feedback_button/word_count_validator.rb
europeana-feedback-button-0.0.6 app/validators/europeana/feedback_button/word_count_validator.rb