Add #to_h to cookie.rb (#55)

This commit is contained in:
Mike Dalessio 2025-07-26 09:30:19 -04:00 committed by GitHub
commit 61fec67ab3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 46 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| 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,45 @@ 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
now = Time.now
cookie = HTTP::Cookie.new(cookie_values.merge({ max_age: 3600, created_at: now, accessed_at: now }))
expected_hash =
{
accessed_at: now,
created_at: now,
domain: 'rubyforge.org',
expires: nil,
for_domain: true,
httponly: cookie.httponly?,
max_age: 3600,
name: 'Foo',
path: '/',
secure: cookie.secure?,
value: 'Bar',
}
assert_equal expected_hash, cookie.to_h
# exercise expires/max_age interaction
cookie = HTTP::Cookie.new(cookie_values.merge({ expires: now, created_at: now, accessed_at: now }))
expected_hash =
{
accessed_at: now,
created_at: now,
domain: 'rubyforge.org',
expires: now,
for_domain: true,
httponly: cookie.httponly?,
max_age: nil,
name: 'Foo',
path: '/',
secure: cookie.secure?,
value: 'Bar',
}
assert_equal expected_hash, cookie.to_h
end
end