Class: Probity::ResponseValidatorMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/probity/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ ResponseValidatorMiddleware

Returns a new instance of ResponseValidatorMiddleware.



5
6
7
8
# File 'lib/probity/middleware.rb', line 5

def initialize(app, options = {})
  @app = app
  @options = options
end

Instance Method Details

#blank_body(body, validator) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/probity/middleware.rb', line 35

def blank_body(body, validator)
  case @options[:blank_body]
  when nil, :validate
    validator.call(body)
  when :raise
    raise 'Response with an empty body'
  when :ignore
  end
end

#blank_string?(str) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/probity/middleware.rb', line 31

def blank_string?(str)
  ! str[/\S/]
end

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/probity/middleware.rb', line 10

def call(env)
  status, headers, response = @app.call(env)
  content_type = response.respond_to?(:content_type) ? response.content_type : headers["Content-Type"]
  validator = Probity.validators[content_type]
  if validator
    body = response.respond_to?(:body) ? response.body : response.join("")
    validate(body, validator)
  else
    missing_validator(content_type)
  end
  [status, headers, response]
end

#missing_validator(content_type) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/probity/middleware.rb', line 45

def missing_validator(content_type)
  error = "No validator defined for #{content_type}. Fix this by putting `#{self.class}.validators['#{content_type}'] = Proc.new do |body| ... end` in a test initializer."
  case @options[:missing_validator]
  when nil, :raise
    raise error
  when :warn
    warn(error)
  when :ignore
  end
end

#validate(body, validator) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/probity/middleware.rb', line 23

def validate(body, validator)
  if blank_string?(body)
    blank_body(body, validator)
  else
    validator.call(body)
  end
end