Class: Faraday::Request::UrlEncoded

Inherits:
Middleware show all
Defined in:
lib/faraday/request/url_encoded.rb

Overview

Middleware for supporting urlencoded requests.

Constant Summary collapse

CONTENT_TYPE =
'Content-Type'

Constants inherited from Middleware

Middleware::DEFAULT_OPTIONS, Middleware::LOCK

Class Attribute Summary collapse

Attributes inherited from Middleware

#app, #options

Instance Method Summary collapse

Methods inherited from Middleware

#close, default_options, default_options=, #initialize

Methods included from MiddlewareRegistry

#lookup_middleware, #register_middleware, #registered_middleware, #unregister_middleware

Constructor Details

This class inherits a constructor from Faraday::Middleware

Class Attribute Details

.mime_typeObject

Returns the value of attribute mime_type.



12
13
14
# File 'lib/faraday/request/url_encoded.rb', line 12

def mime_type
  @mime_type
end

Instance Method Details

#call(env) ⇒ Object

Encodes as "application/x-www-form-urlencoded" if not already encoded or of another type.

Parameters:



20
21
22
23
24
25
26
# File 'lib/faraday/request/url_encoded.rb', line 20

def call(env)
  match_content_type(env) do |data|
    params = Faraday::Utils::ParamsHash[data]
    env.body = params.to_query(env.params_encoder)
  end
  @app.call env
end

#match_content_type(env) {|request_body| ... } ⇒ Object

Parameters:

Yields:

  • (request_body)

    Body of the request



30
31
32
33
34
35
36
37
# File 'lib/faraday/request/url_encoded.rb', line 30

def match_content_type(env)
  return unless process_request?(env)

  env.request_headers[CONTENT_TYPE] ||= self.class.mime_type
  return if env.body.respond_to?(:to_str) || env.body.respond_to?(:read)

  yield(env.body)
end

#process_request?(env) ⇒ Boolean

Returns True if the request has a body and its Content-Type is urlencoded.

Parameters:

Returns:

  • (Boolean)

    True if the request has a body and its Content-Type is urlencoded.



43
44
45
46
# File 'lib/faraday/request/url_encoded.rb', line 43

def process_request?(env)
  type = request_type(env)
  env.body && (type.empty? || (type == self.class.mime_type))
end

#request_type(env) ⇒ String

Parameters:

Returns:

  • (String)


51
52
53
54
55
# File 'lib/faraday/request/url_encoded.rb', line 51

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