Class: Sinatra::Chiro::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatra/chiro/validate.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoints) ⇒ Validation

Returns a new instance of Validation.



8
9
10
# File 'lib/sinatra/chiro/validate.rb', line 8

def initialize(endpoints)
  @endpoints = endpoints
end

Instance Attribute Details

#endpointsObject (readonly)

Returns the value of attribute endpoints.



6
7
8
# File 'lib/sinatra/chiro/validate.rb', line 6

def endpoints
  @endpoints
end

Instance Method Details

#validate(params, env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/sinatra/chiro/validate.rb', line 12

def validate(params, env)
  _, path = env['sinatra.route'].split

  endpoint = endpoints.select { |d| d.path == path }.flatten.first
  return if endpoint.nil?

  all_given = params.dup
  all_given.delete('captures')
  all_given.delete('splat')

  all_params = endpoint.named_params + endpoint.query_params + endpoint.forms

  allowed_params = []
  errors = []

  all_params.each do |parameter|
    unless all_given[parameter.name_display].nil?
      errors << parameter.validate(all_given)
    end
    if !parameter.optional
      errors << "must include a #{parameter.name_display} parameter" if all_given[parameter.name_display].nil?
    end
    allowed_params << parameter.name_display
  end

  all_given.map { |k, _| k.to_s}.each do |param|
    errors << "#{param} is not a valid parameter" if !allowed_params.include?(param)
  end

  if !errors.compact.empty? then
    JSON.dump ({:validation_errors => errors.compact})
  end
end