Sha256: 916cb0e87fa397b3a7b939648950a3a130a6a5e8bb958fec39fdba3bd9dc1b54

Contents?: true

Size: 1.07 KB

Versions: 3

Compression:

Stored size: 1.07 KB

Contents

module Grape
  module Validations
    class AllowBlankValidator < Base
      def validate_param!(attr_name, params)
        return if (options_key?(:value) ? @option[:value] : @option) || !params.is_a?(Hash)

        value = params[attr_name]
        value = value.strip if value.respond_to?(:strip)

        key_exists = params.key?(attr_name)

        if @scope.root?
          # root scope. validate if it's a required param. if it's optional, validate only if key exists in hash
          should_validate = @required || key_exists
        else # nested scope
          should_validate = # required param, and scope contains some values (if scoping element contains no values, treat as blank)
            (@required && params.present?) ||
            # optional param but key inside scoping element exists
            (!@required && params.key?(attr_name))
        end

        return unless should_validate

        return if value == false || value.present?

        fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: message(:blank)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
grape-0.16.2 lib/grape/validations/validators/allow_blank.rb
grape-0.16.1 lib/grape/validations/validators/allow_blank.rb
grape-0.15.0 lib/grape/validations/validators/allow_blank.rb