Module: Sinatra::Validation::Helpers

Defined in:
lib/sinatra/validation.rb

Instance Method Summary collapse

Instance Method Details

#validates(options = {}, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/sinatra/validation.rb', line 28

def validates(options = {}, &block)
  schema = Class.new(Dry::Validation::Contract, &block).new
  validation = schema.call(params)
  result = Result.new(Sinatra::IndifferentHash[validation.to_h])
    .with_message(validation.errors)

  if options[:filter_unpermitted_params] || settings.filter_unpermitted_params
    params.replace validation.to_h
  end

  if options[:silent] || settings.silent_validation
    return result
  end

  if validation.failure?
    raise InvalidParameterError.new(result)
  end

  result
rescue InvalidParameterError => exception
  if options[:raise] || settings.raise_sinatra_validation_exception
    raise exception
  end

  errors = exception.result.messages
  error = errors.first

  if content_type && content_type.match(mime_type(:json))
    error = { errors: errors }.to_json
  end

  halt 400, error
end