class Probity::ResponseValidatorMiddleware

Public Class Methods

new(app, options = {}) click to toggle source
# File lib/probity/middleware.rb, line 5
def initialize(app, options = {})
  @app = app
  @options = options
end

Public Instance Methods

blank_body(body, validator) click to toggle source
# 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) click to toggle source
# File lib/probity/middleware.rb, line 31
def blank_string?(str)
  ! str[/\S/]
end
call(env) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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