Sha256: 14d30407c104b9da65959a9d0a3c1e1a28836659331884dfd5c8e05a7bea6504

Contents?: true

Size: 819 Bytes

Versions: 5

Compression:

Stored size: 819 Bytes

Contents

require 'faraday'



module Saddle::Middleware
  module Request

    # Request middleware that encodes the body as JSON.
    #
    # Make sure you set request[:request_style] = :json
    # for it to be activated.

    class JsonEncoded < Faraday::Middleware
      CONTENT_TYPE = 'Content-Type'.freeze
      MIME_TYPE    = 'application/json'.freeze

      dependency do
        require 'json' unless defined?(::JSON)
      end

      def call(env)
        if env[:request][:request_style] == :json
          # Make sure we're working with a valid body that's not a String
          if env[:body] and !env[:body].respond_to?(:to_str)
            env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
            env[:body] = ::JSON.dump(env[:body])
          end
        end
        @app.call env
      end
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
saddle-0.0.12 lib/saddle/middleware/request/encode_json.rb
saddle-0.0.11 lib/saddle/middleware/request/encode_json.rb
saddle-0.0.10 lib/saddle/middleware/request/encode_json.rb
saddle-0.0.7 lib/saddle/middleware/request/encode_json.rb
saddle-0.0.6 lib/saddle/middleware/request/encode_json.rb