Class: Grape::Validations::AllowBlankValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/grape/validations/validators/allow_blank.rb

Instance Attribute Summary

Attributes inherited from Base

#attrs

Instance Method Summary collapse

Methods inherited from Base

convert_to_short_name, inherited, #initialize, #validate!

Constructor Details

This class inherits a constructor from Grape::Validations::Base

Instance Method Details

#validate_param!(attr_name, params) ⇒ Object


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/grape/validations/validators/allow_blank.rb', line 4

def validate_param!(attr_name, params)
  return if @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

  unless value.present?
    fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message_key: :blank
  end
end