Sha256: c96708284ebaa68509fd566ab54a46a96f6f271d0898d49266d2d29b5a5a82d4

Contents?: true

Size: 1.53 KB

Versions: 6

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

module Faraday
  class Request
    # Middleware for supporting urlencoded requests.
    class UrlEncoded < Faraday::Middleware
      CONTENT_TYPE = 'Content-Type' unless defined? CONTENT_TYPE

      class << self
        attr_accessor :mime_type
      end
      self.mime_type = 'application/x-www-form-urlencoded'

      # Encodes as "application/x-www-form-urlencoded" if not already encoded or
      # of another type.
      #
      # @param env [Faraday::Env]
      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

      # @param env [Faraday::Env]
      # @yield [request_body] Body of the request
      def match_content_type(env)
        return unless process_request?(env)

        env.request_headers[CONTENT_TYPE] ||= self.class.mime_type
        yield(env.body) unless env.body.respond_to?(:to_str)
      end

      # @param env [Faraday::Env]
      #
      # @return [Boolean] True if the request has a body and its Content-Type is
      #                   urlencoded.
      def process_request?(env)
        type = request_type(env)
        env.body && (type.empty? || (type == self.class.mime_type))
      end

      # @param env [Faraday::Env]
      #
      # @return [String]
      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

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
tdiary-5.1.1 vendor/bundle/ruby/2.7.0/gems/faraday-1.0.0/lib/faraday/request/url_encoded.rb
faraday-1.0.0 lib/faraday/request/url_encoded.rb
faraday-0.16.2 lib/faraday/request/url_encoded.rb
faraday-0.16.1 lib/faraday/request/url_encoded.rb
faraday-0.16.0 lib/faraday/request/url_encoded.rb
faraday-1.0.0.pre.rc1 lib/faraday/request/url_encoded.rb