Class: Reaxar::Middleware::Cookies

Inherits:
MiddlewareAbstract show all
Defined in:
lib/reaxar/middleware/cookies.rb

Overview

Middleware to manage HTTP cookies for requests and responses.

This middleware loads cookies from a cookie jar file on initialization, attaches cookies to outgoing requests, updates the cookie jar with any ‘Set-Cookie` headers received in responses, and saves the updated jar back to file.

Examples:

Usage in HTTP client middleware stack

client.use Reaxar::Middleware::Cookies, jar_file: './cookies.yml'

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ void

Initializes the Cookies middleware.

Loads the cookie jar from the specified file if it exists.

Parameters:

  • args (Hash)

    Arguments for configuration.

Options Hash (args):

  • :jar_file (String)

    Path to the cookie jar file.



25
26
27
28
29
# File 'lib/reaxar/middleware/cookies.rb', line 25

def initialize(args) # rubocop:disable Lint/MissingSuper
  @jar_file = args[:jar_file]
  @jar = HTTP::CookieJar.new
  @jar.load(@jar_file) if File.exist?(@jar_file)
end

Instance Method Details

#process_request(request) ⇒ HTTP::Request

Processes the outgoing HTTP request to add cookies.

Adds a ‘Cookie` header containing all relevant cookies from the jar matching the request URI.

Parameters:

  • request (HTTP::Request)

    The HTTP request to process.

Returns:

  • (HTTP::Request)

    The modified request with cookies added.



38
39
40
41
# File 'lib/reaxar/middleware/cookies.rb', line 38

def process_request(request)
  request.headers['cookie'] = HTTP::Cookie.cookie_value(@jar.cookies(request.uri))
  request
end

#process_response(response, request) ⇒ HTTP::Response

Processes the incoming HTTP response to update the cookie jar.

Parses all ‘Set-Cookie` headers from the response and adds them to the jar. Saves the updated cookie jar to the jar file.

Parameters:

  • response (HTTP::Response)

    The HTTP response received.

  • request (HTTP::Request)

    The original HTTP request sent.

Returns:

  • (HTTP::Response)

    The unmodified response.



51
52
53
54
55
56
57
# File 'lib/reaxar/middleware/cookies.rb', line 51

def process_response(response, request)
  response.headers['set-cookie']&.each do |value|
    @jar.parse(value, request[:uri])
  end
  @jar.save(@jar_file)
  response
end