Skip to content

Commit 3b7ccfd

Browse files
lzapjeremyevans
authored andcommitted
Optimize URI#hostname and URI#hostname=
1 parent 3bd2bcc commit 3b7ccfd

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

lib/uri/generic.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,7 @@ def host=(v)
643643
#
644644
def hostname
645645
v = self.host
646-
/\A\[(.*)\]\z/ =~ v ? $1 : v
646+
v&.start_with?('[') && v.end_with?(']') ? v[1..-2] : v
647647
end
648648

649649
# Sets the host part of the URI as the argument with brackets for IPv6 addresses.
@@ -659,7 +659,7 @@ def hostname
659659
# it is wrapped with brackets.
660660
#
661661
def hostname=(v)
662-
v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
662+
v = "[#{v}]" if !(v&.start_with?('[') && v&.end_with?(']')) && v&.index(':')
663663
self.host = v
664664
end
665665

test/uri/test_generic.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,8 +799,12 @@ def test_ipv6
799799

800800
u = URI("http://foo/bar")
801801
assert_equal("http://foo/bar", u.to_s)
802+
u.hostname = "[::1]"
803+
assert_equal("http://[::1]/bar", u.to_s)
802804
u.hostname = "::1"
803805
assert_equal("http://[::1]/bar", u.to_s)
806+
u.hostname = ""
807+
assert_equal("http:///bar", u.to_s)
804808
end
805809

806810
def test_build

0 commit comments

Comments
 (0)