Skip to content

Commit 48b9465

Browse files
committed
Add URI::Generic#deconstruct and URI::Generic#deconstruct_keys
1 parent 89ab4f1 commit 48b9465

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lib/uri/generic.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1583,5 +1583,42 @@ def self.use_proxy?(hostname, addr, port, no_proxy) # :nodoc:
15831583
}
15841584
true
15851585
end
1586+
1587+
# Returns an Array of the components
1588+
def deconstruct
1589+
component_ary
1590+
end
1591+
1592+
#
1593+
# == Args
1594+
#
1595+
# +array_of_names_or_nil+::
1596+
# Array of names of components to be included in the result.
1597+
# If nil, all components are included.
1598+
#
1599+
# == Description
1600+
#
1601+
# Returns a Hash of the components.
1602+
#
1603+
# == Usage
1604+
#
1605+
# require 'uri'
1606+
#
1607+
# uri = URI.parse('http://my.example.com/main.rbx?page=1')
1608+
# uri.deconstruct_keys([:scheme, :host, :path])
1609+
# # => { :scheme => 'http', :host => 'my.example.com', :path => '/main.rbx' }
1610+
# uri.deconstruct_keys(nil)
1611+
# # => { :scheme => 'http', :userinfo => nil, :host => 'my.example.com', :port => 80, :path => '/main.rbx', :query => 'page=1', :fragment => nil }
1612+
#
1613+
def deconstruct_keys(array_of_names_or_nil)
1614+
components = if array_of_names_or_nil.nil?
1615+
component
1616+
else
1617+
array_of_names_or_nil & component
1618+
end
1619+
components.each_with_object({}) do |c, h|
1620+
h[c] = self.__send__(c)
1621+
end
1622+
end
15861623
end
15871624
end

test/uri/test_generic.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -977,6 +977,18 @@ def test_use_proxy_p
977977
end
978978
end
979979

980+
def test_deconstruct
981+
u = URI.parse('http://example.com/path')
982+
assert_equal uri_to_ary(u), u.deconstruct
983+
end
984+
985+
def test_deconstruct_keys
986+
u = URI.parse('http://example.com/path')
987+
assert_equal({ host: 'example.com', port: 80 }, u.deconstruct_keys(%i[host port]))
988+
assert_equal({ scheme: 'http', host: 'example.com', port: 80, path: '/path',
989+
query: nil, fragment: nil, userinfo: nil }, u.deconstruct_keys(nil))
990+
end
991+
980992
class CaseInsensitiveEnv
981993
def initialize(h={})
982994
@h = {}

0 commit comments

Comments
 (0)