Sha256: 2927b2803051530bd45da3642862dbdde648a6b20e5af70f70d2e22463f6b099

Contents?: true

Size: 1.19 KB

Versions: 6

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

# This validator takes care of ensuring the validated attributes are long enough
# and not too long. The difference to the Rails length validator is that this
# allows the minimum and maximum values to be lambdas allowing us to fetch the
# maximum length dynamically for each paragraphs component.
class ParagraphLengthValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.blank?

    validate_min_length(record, attribute, value)
    validate_max_length(record, attribute, value)
  end

  private

  def validate_min_length(record, attribute, value)
    min = options[:minimum] || nil
    min = min.call(record) if min.respond_to?(:call)
    if min && min.positive? && value.length < min
      record.errors.add(
        attribute,
        options[:message] || :too_short,
        count: min
      )
    end
  end

  def validate_max_length(record, attribute, value)
    max = options[:maximum] || nil
    max = max.call(record) if max.respond_to?(:call)
    if max && max.positive? && value.length > max
      record.errors.add(
        attribute,
        options[:message] || :too_long,
        count: max
      )
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
decidim-enhanced_textwork-1.0.5 app/validators/paragraph_length_validator.rb
decidim-enhanced_textwork-1.0.4 app/validators/paragraph_length_validator.rb
decidim-enhanced_textwork-1.0.3 app/validators/paragraph_length_validator.rb
decidim-enhanced_textwork-1.0.2 app/validators/paragraph_length_validator.rb
decidim-enhanced_textwork-1.0.1 app/validators/paragraph_length_validator.rb
decidim-enhanced_textwork-1.0.0 app/validators/paragraph_length_validator.rb