Class: TentClient::Middleware::EncodeJson

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/tent-client/middleware/encode_json.rb

Overview

Constant Summary collapse

CONTENT_TYPE_HEADER =
'Content-Type'.freeze

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
# File 'lib/tent-client/middleware/encode_json.rb', line 14

def call(env)
  match_content_type(env) do |data|
    env[:body] = encode data
  end
  @app.call env
end

#encode(data) ⇒ Object



21
22
23
# File 'lib/tent-client/middleware/encode_json.rb', line 21

def encode(data)
  Yajl::Encoder.encode(data)
end

#has_body?(env) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/tent-client/middleware/encode_json.rb', line 36

def has_body?(env)
  body = env[:body] and !(body.respond_to?(:to_str) and body.empty?)
end

#match_content_type(env) ⇒ Object



25
26
27
28
29
# File 'lib/tent-client/middleware/encode_json.rb', line 25

def match_content_type(env)
  if process_request?(env)
    yield env[:body] unless env[:body].respond_to?(:to_str)
  end
end

#process_request?(env) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
34
# File 'lib/tent-client/middleware/encode_json.rb', line 31

def process_request?(env)
  type = request_type(env)
  has_body?(env) and (type.empty? or type =~ /\bjson\Z/)
end

#request_type(env) ⇒ Object



40
41
42
43
44
# File 'lib/tent-client/middleware/encode_json.rb', line 40

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