Skip to content

Conversation

@baweaver
Copy link
Contributor

@baweaver baweaver commented Nov 9, 2025

This PR adds deconstruct_keys to Net::HTTPResponse, enabling pattern matching on HTTP response attributes.

(Moved from ruby/ruby#15109)

Usage

response = Net::HTTP.get_response(uri)
case response
in code: '200', content_type: /json/
  JSON.parse(response.body)
in code: '404'
  handle_not_found
end

Implementation

• Added PATTERN_MATCHING_KEYS constant defining valid keys: code, message, http_version, body, content_type
• Implemented deconstruct_keys following Ruby pattern matching best practices
• Avoids expensive operations by accessing @body directly rather than calling the body method
• Returns only requested keys when specified, all valid keys when keys is nil

Implements deconstruct_keys to enable pattern matching on HTTP responses
based on status code, content type, and other response attributes.

Example:
  case response
  in code: '200', content_type: /json/
    JSON.parse(response.body)
  in code: '404'
    handle_not_found
  end
res['content-type'] = 'application/json'

begin
matched = instance_eval <<~RUBY, __FILE__, __LINE__ + 1
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a similar trick as to what we had used around pattern matching for the 2.6 to 2.7 push, so I'm repeating it here. The other methods should function even without syntax bridges like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant