Sha256: 2c175c58fc2384d762e088fe0558a49c24fdd3b06430449076d81492907f2acd

Contents?: true

Size: 782 Bytes

Versions: 5

Compression:

Stored size: 782 Bytes

Contents

module Redd
  # The module that contains middleware that alters the Faraday response.
  module Response
    # Faraday Middleware that parses JSON using Oj.
    class ParseJson < Faraday::Middleware
      dependency do
        require "oj" unless defined?(::Oj)
      end

      # Call the middleware.
      # @param faraday
      def call(faraday)
        @app.call(faraday).on_complete do |env|
          env[:body] = parse(env[:body])
        end
      end

      private

      # Parse a JSON string and return a symbolized hash.
      #
      # @param [String] body The JSON string to parse.
      # @return [Hash] A symbolized parsed JSON hash.
      def parse(body)
        Oj.load(body, symbol_keys: true)
      rescue Oj::ParseError
        body
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
redd-0.1.4 lib/redd/response/parse_json.rb
redd-0.1.3 lib/redd/response/parse_json.rb
redd-0.1.2 lib/redd/response/parse_json.rb
redd-0.1.1 lib/redd/response/parse_json.rb
redd-0.1.0 lib/redd/response/parse_json.rb