Class: FaradayMiddleware::Jsons::Decoder

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/faraday_middleware/jsons/response/decoder.rb

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Decoder.


3
4
5
6
7
8
9
# File 'lib/faraday_middleware/jsons/response/decoder.rb', line 3

def initialize(app, options = {})
  super(app)

  @raise_error    = options[:raise_error]    || false
  @symbolize_keys = options[:symbolize_keys] || false
  @content_type   = options[:content_type]   || %r!^application/(.*\+)?json!
end

Instance Method Details

#call(env) ⇒ Object


11
12
13
14
15
16
17
# File 'lib/faraday_middleware/jsons/response/decoder.rb', line 11

def call(env)
  @app.call(env).on_complete do |env|
    if has_body?(env) && match_content_type?(env)
      env[:body] = parse(env[:body])
    end
  end
end

#parse(body) ⇒ Object


19
20
21
22
23
24
25
26
# File 'lib/faraday_middleware/jsons/response/decoder.rb', line 19

def parse(body)
  begin
    ::MultiJson.load(body, symbolize_keys: @symbolize_keys)
  rescue => e
    raise e if @raise_error
    body
  end
end