From 48b94650247e043607e15d4ebbfcb93023a0cc3e Mon Sep 17 00:00:00 2001 From: miyucy Date: Wed, 22 Feb 2023 03:19:09 +0900 Subject: [PATCH] Add URI::Generic#deconstruct and URI::Generic#deconstruct_keys --- lib/uri/generic.rb | 37 +++++++++++++++++++++++++++++++++++++ test/uri/test_generic.rb | 12 ++++++++++++ 2 files changed, 49 insertions(+) diff --git a/lib/uri/generic.rb b/lib/uri/generic.rb index 69698c4..7de519f 100644 --- a/lib/uri/generic.rb +++ b/lib/uri/generic.rb @@ -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 diff --git a/test/uri/test_generic.rb b/test/uri/test_generic.rb index 3897c3d..c96d469 100644 --- a/test/uri/test_generic.rb +++ b/test/uri/test_generic.rb @@ -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 = {}