Class: FaradayStack::ResponseMiddleware

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/faraday_stack/response_middleware.rb

Overview

A base class for middleware that parses responses

Constant Summary collapse

CONTENT_TYPE =
'Content-Type'.freeze

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app = nil, options = {}) ⇒ ResponseMiddleware

Returns a new instance of ResponseMiddleware.



21
22
23
24
25
# File 'lib/faraday_stack/response_middleware.rb', line 21

def initialize(app = nil, options = {})
  super(app)
  @options = options
  @content_types = Array(options[:content_type])
end

Class Attribute Details

.parserObject

Returns the value of attribute parser.



7
8
9
# File 'lib/faraday_stack/response_middleware.rb', line 7

def parser
  @parser
end

Class Method Details

.define_parser(&block) ⇒ Object

Stores a block that receives the body and should return a parsed result



11
12
13
# File 'lib/faraday_stack/response_middleware.rb', line 11

def self.define_parser(&block)
  @parser = block
end

.inherited(subclass) ⇒ Object



15
16
17
18
19
# File 'lib/faraday_stack/response_middleware.rb', line 15

def self.inherited(subclass)
  super
  subclass.load_error = self.load_error if subclass.respond_to? :load_error=
  subclass.parser = self.parser
end

Instance Method Details

#on_complete(env) ⇒ Object

Override this to modify the environment after the response has finished.



28
29
30
31
32
# File 'lib/faraday_stack/response_middleware.rb', line 28

def on_complete(env)
  if process_response_type?(response_type(env)) and parse_response?(env)
    env[:body] = parse(env[:body])
  end
end

#parse(body) ⇒ Object

Parses the response body and returns the result. Instead of overriding this method, consider using ‘define_parser`



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/faraday_stack/response_middleware.rb', line 36

def parse(body)
  if self.class.parser
    begin
      self.class.parser.call(body)
    rescue
      raise Faraday::Error::ParsingError, $!
    end
  else
    body
  end
end

#parse_response?(env) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/faraday_stack/response_middleware.rb', line 60

def parse_response?(env)
  env[:body].respond_to? :to_str
end

#process_response_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
57
58
# File 'lib/faraday_stack/response_middleware.rb', line 54

def process_response_type?(type)
  @content_types.empty? or @content_types.any? { |pattern|
    Regexp === pattern ? type =~ pattern : type == pattern
  }
end

#response_type(env) ⇒ Object



48
49
50
51
52
# File 'lib/faraday_stack/response_middleware.rb', line 48

def response_type(env)
  type = env[:response_headers][CONTENT_TYPE].to_s
  type = type.split(';', 2).first if type.index(';')
  type
end