Sha256: 3aa2466a3c08c7e8c5bc4c8475979a19577c25e8e2d517e5f9c9b61931771291

Contents?: true

Size: 1.04 KB

Versions: 20

Compression:

Stored size: 1.04 KB

Contents

# encoding: utf-8

require 'faraday'

module Nimbu
  class Request::Json < Faraday::Middleware

    CONTENT_TYPE = 'Content-Type'.freeze
    MIME_TYPE    = 'application/json'.freeze

    dependency 'multi_json'

    def call(env)
      if request_with_body?(env)
        env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
        env[:body] = encode_body env unless env[:body].respond_to?(:to_str)
      end
      @app.call env
    end

    def encode_body(env)
      if MultiJson.respond_to?(:dump)
        MultiJson.dump env[:body]
      else
        MultiJson.encode env[:body]
      end
    end

    def request_with_body?(env)
      type = request_type(env)
      has_body?(env) and (type.empty? or type == MIME_TYPE)
    end

    # Don't encode bodies in string form
    def has_body?(env)
      body = env[:body] and !(body.respond_to?(:to_str) and body.empty?)
    end

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

  end # Request::Json
end # Nimbu

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
nimbu-api-0.5.0 lib/nimbu-api/request/json.rb
nimbu-api-0.4.4 lib/nimbu-api/request/json.rb
nimbu-api-0.4.3 lib/nimbu-api/request/json.rb
nimbu-api-0.4.2 lib/nimbu-api/request/json.rb
nimbu-api-0.4.1 lib/nimbu-api/request/json.rb
nimbu-api-0.4.0 lib/nimbu-api/request/json.rb
nimbu-api-0.3.0 lib/nimbu-api/request/json.rb
nimbu-api-0.2.1 lib/nimbu-api/request/json.rb
nimbu-api-0.2 lib/nimbu-api/request/json.rb
nimbu-api-0.2.beta.3 lib/nimbu-api/request/json.rb
nimbu-api-0.2.beta.2 lib/nimbu-api/request/json.rb
nimbu-api-0.2.beta.1 lib/nimbu-api/request/json.rb
nimbu-api-0.2.beta lib/nimbu-api/request/json.rb
nimbu-api-0.1.5 lib/nimbu-api/request/json.rb
nimbu-api-0.1.4 lib/nimbu-api/request/json.rb
nimbu-api-0.1.3 lib/nimbu-api/request/json.rb
nimbu-api-0.1.1 lib/nimbu-api/request/json.rb
nimbu-api-0.1 lib/nimbu-api/request/json.rb
nimbu-api-0.0.2 lib/nimbu-api/request/json.rb
nimbu-api-0.0.1 lib/nimbu-api/request/json.rb