Class: Terminal::RequestExt::EncodeJson
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Terminal::RequestExt::EncodeJson
- Defined in:
- lib/terminal/request/encode_json.rb
Constant Summary collapse
- CONTENT_TYPE =
'Content-Type'.freeze
- MIME_TYPE =
'application/json'.freeze
Instance Method Summary collapse
- #call(env) ⇒ Object
- #encode(data) ⇒ Object
- #has_body?(env) ⇒ Boolean
- #match_content_type(env) ⇒ Object
- #process_request?(env) ⇒ Boolean
- #request_type(env) ⇒ Object
Instance Method Details
#call(env) ⇒ Object
15 16 17 18 19 20 |
# File 'lib/terminal/request/encode_json.rb', line 15 def call(env) match_content_type(env) do |data| env[:body] = encode data end @app.call env end |
#encode(data) ⇒ Object
22 23 24 |
# File 'lib/terminal/request/encode_json.rb', line 22 def encode(data) ::JSON.dump data end |
#has_body?(env) ⇒ Boolean
38 39 40 |
# File 'lib/terminal/request/encode_json.rb', line 38 def has_body?(env) body = env[:body] and !(body.respond_to?(:to_str) and body.empty?) end |
#match_content_type(env) ⇒ Object
26 27 28 29 30 31 |
# File 'lib/terminal/request/encode_json.rb', line 26 def match_content_type(env) if process_request?(env) env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE yield env[:body] unless env[:body].respond_to?(:to_str) end end |
#process_request?(env) ⇒ Boolean
33 34 35 36 |
# File 'lib/terminal/request/encode_json.rb', line 33 def process_request?(env) type = request_type(env) has_body?(env) and (type.empty? or type == MIME_TYPE) end |
#request_type(env) ⇒ Object
42 43 44 45 46 |
# File 'lib/terminal/request/encode_json.rb', line 42 def request_type(env) type = env[:request_headers][CONTENT_TYPE].to_s type = type.split(';', 2).first if type.index(';') type end |