class Grape::Validations::CoerceValidator

Public Instance Methods

validate_param!(attr_name, params) click to toggle source
# File lib/grape/validations/coerce.rb, line 8
def validate_param!(attr_name, params)
  raise Grape::Exceptions::Validation, param: @scope.full_name(attr_name), message_key: :coerce unless params.is_a? Hash
  new_value = coerce_value(@option, params[attr_name])
  if valid_type?(new_value)
    params[attr_name] = new_value
  else
    raise Grape::Exceptions::Validation, param: @scope.full_name(attr_name), message_key: :coerce
  end
end

Private Instance Methods

_valid_array_type?(type, values) click to toggle source
# File lib/grape/validations/coerce.rb, line 22
def _valid_array_type?(type, values)
  values.all? do |val|
    _valid_single_type?(type, val)
  end
end
_valid_single_type?(klass, val) click to toggle source
# File lib/grape/validations/coerce.rb, line 28
def _valid_single_type?(klass, val)
  # allow nil, to ignore when a parameter is absent
  return true if val.nil?
  if klass == Virtus::Attribute::Boolean
    val.is_a?(TrueClass) || val.is_a?(FalseClass)
  elsif klass == Rack::Multipart::UploadedFile
    val.is_a?(Hashie::Mash) && val.key?(:tempfile)
  else
    val.is_a?(klass)
  end
end
coerce_value(type, val) click to toggle source
# File lib/grape/validations/coerce.rb, line 48
def coerce_value(type, val)
  # Don't coerce things other than nil to Arrays or Hashes
  return val || [] if type == Array
  return val || {} if type == Hash

  converter = Virtus::Attribute.build(type)
  converter.coerce(val)

# not the prettiest but some invalid coercion can currently trigger
# errors in Virtus (see coerce_spec.rb:75)
rescue
  InvalidValue.new
end
valid_type?(val) click to toggle source
# File lib/grape/validations/coerce.rb, line 40
def valid_type?(val)
  if @option.is_a?(Array)
    _valid_array_type?(@option[0], val)
  else
    _valid_single_type?(@option, val)
  end
end