Add #to_h to cookie.rb

This commit is contained in:
Luke Hill 2025-07-11 17:09:35 +01:00 committed by Mike Dalessio
parent 467b84fedf
commit 2ac1692e41
No known key found for this signature in database
2 changed files with 31 additions and 0 deletions

View file

@ -655,6 +655,11 @@ class HTTP::Cookie
end
include Comparable
# Hash serialization helper for use back into other libraries (Like Selenium)
def to_h
PERSISTENT_PROPERTIES.each_with_object({}) { |property, hash| [property.to_sym] => instance_variable_get("@#{property}") }
end
# YAML serialization helper for Syck.
def to_yaml_properties
PERSISTENT_PROPERTIES.map { |name| "@#{name}" }

View file

@ -1168,4 +1168,30 @@ class TestHTTPCookie < Test::Unit::TestCase
assert_equal true, HTTP::Cookie.path_match?('/admin', '/admin/')
assert_equal true, HTTP::Cookie.path_match?('/admin', '/admin/index')
end
def test_to_h_coercion
now = Time.now
cookie = HTTP::Cookie.new(cookie_values.merge({ expires: now, max_age: 3600, created_at: now, accessed_at: now }))
cookie.keys.each { |key| assert_equal key.class, Symbol }
assert_equal cookie.keys.map(&:to_s), PERSISTENT_PROPERTIES
expected_hash =
{
name: 'Foo',
value: 'Bar',
path: '/',
expires: now,
for_domain: true,
domain: 'rubyforge.org',
origin: 'http://rubyforge.org/',
secure: true,
httponly: true,
max_age: 3600,
created_at: now,
accessed_at: now
}
assert_equal cookie.to_h, expected_hash
end
end