Sha256: 4711e3daf6993eea8bff48d7c85b639a4249d8af71dfdd78001abffa5e82fbb3

Contents?: true

Size: 1.19 KB

Versions: 25

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 proposals component.
class ProposalLengthValidator < 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

25 entries across 25 versions & 1 rubygems

Version Path
decidim-proposals-0.27.0 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.3 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.0.rc2 app/validators/proposal_length_validator.rb
decidim-proposals-0.27.0.rc1 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.2 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.1 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.0 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.0.rc2 app/validators/proposal_length_validator.rb
decidim-proposals-0.26.0.rc1 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.2 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.1 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.0 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.0.rc4 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.0.rc3 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.0.rc2 app/validators/proposal_length_validator.rb
decidim-proposals-0.25.0.rc1 app/validators/proposal_length_validator.rb
decidim-proposals-0.24.3 app/validators/proposal_length_validator.rb
decidim-proposals-0.23.6 app/validators/proposal_length_validator.rb
decidim-proposals-0.24.2 app/validators/proposal_length_validator.rb
decidim-proposals-0.23.5 app/validators/proposal_length_validator.rb