Class: Reaxar::Middleware::Cookies
- Inherits:
-
MiddlewareAbstract
- Object
- MiddlewareAbstract
- Reaxar::Middleware::Cookies
- 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.
Instance Method Summary collapse
-
#initialize(args) ⇒ void
constructor
Initializes the Cookies middleware.
-
#process_request(request) ⇒ HTTP::Request
Processes the outgoing HTTP request to add cookies.
-
#process_response(response, request) ⇒ HTTP::Response
Processes the incoming HTTP response to update the cookie jar.
Constructor Details
#initialize(args) ⇒ void
Initializes the Cookies middleware.
Loads the cookie jar from the specified file if it exists.
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.
38 39 40 41 |
# File 'lib/reaxar/middleware/cookies.rb', line 38 def process_request(request) request.headers['cookie'] = HTTP::Cookie.(@jar.(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.
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 |