Skip to content

Commit 61fec67

Browse files
authored
Add #to_h to cookie.rb (#55)
2 parents 467b84f + 2301380 commit 61fec67

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/http/cookie.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,11 @@ def <=> other
655655
end
656656
include Comparable
657657

658+
# Hash serialization helper for use back into other libraries (Like Selenium)
659+
def to_h
660+
PERSISTENT_PROPERTIES.each_with_object({}) { |property, hash| hash[property.to_sym] = instance_variable_get("@#{property}") }
661+
end
662+
658663
# YAML serialization helper for Syck.
659664
def to_yaml_properties
660665
PERSISTENT_PROPERTIES.map { |name| "@#{name}" }

test/test_http_cookie.rb

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,4 +1168,45 @@ def test_s_path_match?
11681168
assert_equal true, HTTP::Cookie.path_match?('/admin', '/admin/')
11691169
assert_equal true, HTTP::Cookie.path_match?('/admin', '/admin/index')
11701170
end
1171+
1172+
def test_to_h
1173+
now = Time.now
1174+
1175+
cookie = HTTP::Cookie.new(cookie_values.merge({ max_age: 3600, created_at: now, accessed_at: now }))
1176+
expected_hash =
1177+
{
1178+
accessed_at: now,
1179+
created_at: now,
1180+
domain: 'rubyforge.org',
1181+
expires: nil,
1182+
for_domain: true,
1183+
httponly: cookie.httponly?,
1184+
max_age: 3600,
1185+
name: 'Foo',
1186+
path: '/',
1187+
secure: cookie.secure?,
1188+
value: 'Bar',
1189+
}
1190+
1191+
assert_equal expected_hash, cookie.to_h
1192+
1193+
# exercise expires/max_age interaction
1194+
cookie = HTTP::Cookie.new(cookie_values.merge({ expires: now, created_at: now, accessed_at: now }))
1195+
expected_hash =
1196+
{
1197+
accessed_at: now,
1198+
created_at: now,
1199+
domain: 'rubyforge.org',
1200+
expires: now,
1201+
for_domain: true,
1202+
httponly: cookie.httponly?,
1203+
max_age: nil,
1204+
name: 'Foo',
1205+
path: '/',
1206+
secure: cookie.secure?,
1207+
value: 'Bar',
1208+
}
1209+
1210+
assert_equal expected_hash, cookie.to_h
1211+
end
11711212
end

0 commit comments

Comments
 (0)