Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add URI::Generic#deconstruct and URI::Generic#deconstruct_keys #56

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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