Problem constructing a url with uri


#1

I have this, example, code:

require ‘uri’

a = Hash.new
a[“fred”] = 42
a[“tom”] = “dick”

x = URI::HTTP.build( {:host => “fred.com”, :query => a} )
puts x.to_s

Which I was expecting to create a url like
http://fred.com/?fred=42&tom=dick but all I get is

/usr/lib/ruby/1.8/uri/generic.rb:508:in =~': can't convert Hash into String (TypeError) from /usr/lib/ruby/1.8/uri/generic.rb:508:incheck_query’
from /usr/lib/ruby/1.8/uri/generic.rb:523:in query=' from /usr/lib/ruby/1.8/uri/generic.rb:178:ininitialize’
from /usr/lib/ruby/1.8/uri/http.rb:46:in initialize' from /usr/lib/ruby/1.8/uri/generic.rb:125:innew’
from /usr/lib/ruby/1.8/uri/generic.rb:125:in build' from /usr/lib/ruby/1.8/uri/http.rb:36:inbuild’
from x:7

Am I correct in my assumption that :query will take a hash and the
correct arguments or do I need to create my own function to do the
conversion?


#2

On Jun 8, 2006, at 7:34 AM, Peter H. wrote:

   from /usr/lib/ruby/1.8/uri/generic.rb:125:in `build'
   from /usr/lib/ruby/1.8/uri/http.rb:36:in `build'
   from x:7

Am I correct in my assumption that :query will take a hash and the
correct arguments or do I need to create my own function to do the
conversion?

:query appears to have be a string. All it does afaict is tack a ?
with the string for query on the end.

e.g.

URI::HTTP.build(:host => “ruby-lang.org”, :query => “ruby”).to_s
#=> “http://ruby-lang.org?ruby


#3

From looking at the code, it seems to expect the query to be a string in
the appropriate format.

Cheers


#4

Peter H. wrote:

a = Hash.new
a[“fred”] = 42
a[“tom”] = “dick”

x = URI::HTTP.build( {:host => “fred.com”, :query => a} )

:query should be a string – or rather, should respond to #to_str.

q = {:fred => 42, :tom => ‘dick’}
def q.to_str
collect{|name, value| “#{name}=#{value}”}.join(’&’)
end
uri = URI::HTTP.build(:host => “fred.com”, :query => q)

Cheers,
Daniel