uri = URI.parse(the_uri)
hash = CGI.parse(uri.query)
hash["size"] = size.to_s
key_value_pairs = []
hash.each_pair {|key, value| key_value_pairs << "#{key}=#{value}" }
uri.query = key_value_pairs.join("&")
Refactorings
No refactoring yet !
steved
August 21, 2010, August 21, 2010 14:53, permalink
Not sure what you are trying to do or having trouble with ... but URI can handle query params:
require 'uri'
size = 11
uri = URI.parse("http://example.com?size=#{size}")
puts uri.query #=> size=11
puts uri.to_s #=> http://example.com?size=11
Krzysztof Wilczynski
August 21, 2010, August 21, 2010 18:52, permalink
My impression is that you are re-writing the original URI with some of your own overrides, and if that is the case, then try this:
override = { 'size' => 12345, 'foo' => 'quux' }
the_uri = 'http://example.com?size=123&foo=bar&answer=42'
uri = URI.parse(the_uri)
uri.query = CGI.parse(uri.query).collect { |k, v| "#{k}=#{override[k] || v.to_s}" }.join('&')
Adam
August 22, 2010, August 22, 2010 03:10, permalink
uri = URI.parse(the_uri)
uri.query = CGI.parse(uri.query).merge!('size' => size).map { |key,value| URI.escape("#{key}=#{value}") }.join('&')
Krzysztof Wilczynski
August 22, 2010, August 22, 2010 12:29, permalink
Adam += 1 for the .merge! and URI.escape ... time to update my re-factoring a little bit too ...
uri.query = CGI.parse(uri.query).collect { |k, v| URI.escape("#{k}=#{override[k] || v}") }.join('&')
Yury Kotlyarov
August 29, 2010, August 29, 2010 20:46, permalink
addressable gem is the best option
require 'addressable/uri'
uri = Addressable::URI.parse(the_uri)
uri.query_values ||= {}
uri.query_values = uri.query_values.merge('size' => size.to_s)
uri.to_s
Is there some magic i don't know about?