Sha256: 5e1419cf1238054bee699ef453f0d99b52319316298797d405312fa01006c70f

Contents?: true

Size: 1.54 KB

Versions: 4

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

module Grape
  module Validations
    module Validators
      class LengthValidator < Base
        def initialize(attrs, options, required, scope, **opts)
          @min = options[:min]
          @max = options[:max]

          super

          raise ArgumentError, 'min must be an integer greater than or equal to zero' if !@min.nil? && (!@min.is_a?(Integer) || @min.negative?)
          raise ArgumentError, 'max must be an integer greater than or equal to zero' if !@max.nil? && (!@max.is_a?(Integer) || @max.negative?)
          raise ArgumentError, "min #{@min} cannot be greater than max #{@max}" if !@min.nil? && !@max.nil? && @min > @max
        end

        def validate_param!(attr_name, params)
          param = params[attr_name]

          raise ArgumentError, "parameter #{param} does not support #length" unless param.respond_to?(:length)

          return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max)

          raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: build_message)
        end

        def build_message
          if options_key?(:message)
            @option[:message]
          elsif @min && @max
            format I18n.t(:length, scope: 'grape.errors.messages'), min: @min, max: @max
          elsif @min
            format I18n.t(:length_min, scope: 'grape.errors.messages'), min: @min
          else
            format I18n.t(:length_max, scope: 'grape.errors.messages'), max: @max
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
grape-2.1.3 lib/grape/validations/validators/length_validator.rb
grape-2.1.2 lib/grape/validations/validators/length_validator.rb
grape-2.1.1 lib/grape/validations/validators/length_validator.rb
grape-2.1.0 lib/grape/validations/validators/length_validator.rb