diff --git a/lib/string_tools.rb b/lib/string_tools.rb index f8f903e..73954b9 100644 --- a/lib/string_tools.rb +++ b/lib/string_tools.rb @@ -216,4 +216,14 @@ def rublej_propisju(amount) end end extend SumInWords + + module Uri + def add_params_to_url(url, params = nil) + uri = Addressable::URI.parse(url) + uri = Addressable::URI.parse("http://#{url}") unless uri.scheme + uri.query_values = (uri.query_values || {}).merge!(params.stringify_keys) if params.present? + uri.normalize.to_s + end + end + extend Uri end diff --git a/spec/string_tools_spec.rb b/spec/string_tools_spec.rb index 1b737d5..e915674 100644 --- a/spec/string_tools_spec.rb +++ b/spec/string_tools_spec.rb @@ -64,4 +64,47 @@ it { expect(strip_tags_leave_br).to eq('bar
') } end end + + describe '#add_params_to_url' do + subject(:add_params_to_url) { described_class.add_params_to_url(url, params) } + let(:url) { 'http://test.com' } + let(:uri) { 'http://test.com/?param=test' } + + context 'when url with params' do + let(:params) { {'param' => 'test'} } + + it { expect(add_params_to_url).to eq uri } + end + + context 'when optional params not passed' do + it { expect(described_class.add_params_to_url(url)).to eq 'http://test.com/' } + end + + context 'when url not normalized' do + let(:url) { 'http://TesT.com:80' } + let(:params) { {'param' => 'test'} } + + it { expect(add_params_to_url).to eq uri } + end + + context 'when url without scheme' do + let(:url) { 'test.com' } + let(:params) { {'param' => 'test'} } + + it { expect(add_params_to_url).to eq uri } + end + + context 'when url scheme is https' do + let(:url) { 'https://test.com' } + let(:params) { {'param' => 'test'} } + + it { expect(add_params_to_url).to eq 'https://test.com/?param=test' } + end + + context 'when key is a symbol with same value' do + let(:url) { 'http://test.com/?a=b' } + + it { expect(described_class.add_params_to_url(url, a: 'c')).to eq 'http://test.com/?a=c' } + end + end end