I have a URL in a string. What is the most concise way to add some parameters to it?
e.g.
base = 'http://example.com'
uri1 = some_magical_method(base, :p1 => 'v1') # => http://example.com/?p1=v1
uri2 = some_magical_method(uri1, :p2 => 'v2') # => http://example.com/?p1=v1&p2=v2
uri3 = some_magical_method(uri2, :p3 => nil) # => http://example.com/?p1=v1&p2=v2
1) In Ruby?
2) In Rails?
In Rails, where ActiveSupport is available, the easiest way is to construct a hash, then to call #to_query
on it.
>> params = {}
>> params[:foo] = "bar"
>> params[:baz] = "bang"
>> params.to_query
=> "baz=bang&foo=bar"
In plain Ruby, the same applies, but you'll need to write the encoder yourself:
require 'cgi'
def to_query(hsh)
hsh.map {|k, v| "#{k}=#{CGI::escape v}" }.join("&")
end
params = {}
params[:foo] = "bar"
params[:baz] = "bang"
to_query params
=> "baz=bang&foo=bar"
require 'open-uri'
def params_to_query(params)
params.map {|p, v| "#{p}=#{URI.escape(v.to_s)}"}.join('&')
end
def append_url(url, params = {})
uri = URI.parse(url)
uri.query = uri.query.nil? ? params_to_query(params) : [uri.query, params_to_query(params)].join('&') unless params.empty?
uri.to_s
end
puts append_url('http://example.com', {:query => 'my_example'} # "http://example.com?query=my_example"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With