Sha256: 795ac0b0955d8e19c70204d6003787f5cad2c50d370a3bf93565e8c67350cdcc

Contents?: true

Size: 1.12 KB

Versions: 72

Compression:

Stored size: 1.12 KB

Contents

require 'faraday'
require 'json'

module Ably
  module Rest
    module Middleware
      # Encode the body of the message according to the mime type
      class Encoder < ::Faraday::Response::Middleware
        CONTENT_TYPE = 'Content-Type'.freeze unless defined? CONTENT_TYPE

        def call(env)
          encode env if env.body
          @app.call env
        end

        private
        def encode(env)
          env.body = case request_type(env)
          when 'application/x-msgpack'
            to_msgpack(env.body)
          when 'application/json', '', nil
            env.request_headers[CONTENT_TYPE] = 'application/json'
            to_json(env.body)
          else
            env.body
          end
        end

        def to_msgpack(body)
          body.to_msgpack
        end

        def to_json(body)
          if body.kind_of?(String)
            body
          else
            body.to_json
          end
        end

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

Version data entries

72 entries across 72 versions & 2 rubygems

Version Path
ably-0.8.14 lib/ably/rest/middleware/encoder.rb
ably-rest-0.8.13 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-0.8.13 lib/ably/rest/middleware/encoder.rb
ably-0.8.12 lib/ably/rest/middleware/encoder.rb
ably-0.8.11 lib/ably/rest/middleware/encoder.rb
ably-0.8.10 lib/ably/rest/middleware/encoder.rb
ably-rest-0.8.9 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-0.8.9 lib/ably/rest/middleware/encoder.rb
ably-0.8.8 lib/ably/rest/middleware/encoder.rb
ably-0.8.7 lib/ably/rest/middleware/encoder.rb
ably-0.8.6 lib/ably/rest/middleware/encoder.rb
ably-rest-0.8.6 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-rest-0.8.5 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-0.8.5 lib/ably/rest/middleware/encoder.rb
ably-0.8.4 lib/ably/rest/middleware/encoder.rb
ably-rest-0.8.3 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-0.8.3 lib/ably/rest/middleware/encoder.rb
ably-rest-0.8.2 lib/submodules/ably-ruby/lib/ably/rest/middleware/encoder.rb
ably-0.8.2 lib/ably/rest/middleware/encoder.rb
ably-0.8.1 lib/ably/rest/middleware/encoder.rb