Skip to content

Commit

Permalink
Add URI::Generic#deconstruct and URI::Generic#deconstruct_keys
Browse files Browse the repository at this point in the history
  • Loading branch information
miyucy committed Feb 21, 2023
1 parent 89ab4f1 commit 48b9465
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/uri/generic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1583,5 +1583,42 @@ def self.use_proxy?(hostname, addr, port, no_proxy) # :nodoc:
}
true
end

# Returns an Array of the components
def deconstruct
component_ary
end

#
# == Args
#
# +array_of_names_or_nil+::
# Array of names of components to be included in the result.
# If nil, all components are included.
#
# == Description
#
# Returns a Hash of the components.
#
# == Usage
#
# require 'uri'
#
# uri = URI.parse('http://my.example.com/main.rbx?page=1')
# uri.deconstruct_keys([:scheme, :host, :path])
# # => { :scheme => 'http', :host => 'my.example.com', :path => '/main.rbx' }
# uri.deconstruct_keys(nil)
# # => { :scheme => 'http', :userinfo => nil, :host => 'my.example.com', :port => 80, :path => '/main.rbx', :query => 'page=1', :fragment => nil }
#
def deconstruct_keys(array_of_names_or_nil)
components = if array_of_names_or_nil.nil?
component
else
array_of_names_or_nil & component
end
components.each_with_object({}) do |c, h|
h[c] = self.__send__(c)
end
end
end
end
12 changes: 12 additions & 0 deletions test/uri/test_generic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,18 @@ def test_use_proxy_p
end
end

def test_deconstruct
u = URI.parse('http://example.com/path')
assert_equal uri_to_ary(u), u.deconstruct
end

def test_deconstruct_keys
u = URI.parse('http://example.com/path')
assert_equal({ host: 'example.com', port: 80 }, u.deconstruct_keys(%i[host port]))
assert_equal({ scheme: 'http', host: 'example.com', port: 80, path: '/path',
query: nil, fragment: nil, userinfo: nil }, u.deconstruct_keys(nil))
end

class CaseInsensitiveEnv
def initialize(h={})
@h = {}
Expand Down

0 comments on commit 48b9465

Please sign in to comment.