Sha256: 358d26073980b6d4714c38886981efdd5466c25eb2e6b13a4b7dbd29b6eff327

Contents?: true

Size: 1.28 KB

Versions: 28

Compression:

Stored size: 1.28 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 proposals component.
class ProposalLengthValidator < ActiveModel::EachValidator
  include ActionView::Helpers::SanitizeHelper

  def validate_each(record, attribute, value)
    return if value.blank?

    text_value = strip_tags(value)
    validate_min_length(record, attribute, text_value)
    validate_max_length(record, attribute, text_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

28 entries across 28 versions & 1 rubygems

Version Path
decidim-proposals-0.29.1 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.4 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.9 app/validators/proposal_length_validator.rb
decidim-proposals-0.29.0 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.3 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.8 app/validators/proposal_length_validator.rb
decidim-proposals-0.29.0.rc4 app/validators/proposal_length_validator.rb
decidim-proposals-0.29.0.rc3 app/validators/proposal_length_validator.rb
decidim-proposals-0.29.0.rc2 app/validators/proposal_length_validator.rb
decidim-proposals-0.29.0.rc1 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.2 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.7 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.1 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.6 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.10 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.9 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.0 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.5 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.0.rc5 app/validators/proposal_length_validator.rb
decidim-proposals-0.28.0.rc4 app/validators/proposal_length_validator.rb