Steven Xu Steven Xu - 2 years ago 75
Ruby Question

Is there a Ruby library/gem that will generate a URL based on a set of parameters?

Rails' URL generation mechanism (most of which routes through

at some point) allows for the passing of a hash that gets serialized into a query string at least for GET requests. What's the best way to get that sort of functionality, but on top of any base path?

For instance, I'd like to have something like the following:

generate_url('', :q => 'hello world')
# => ''

I could certainly write my own that strictly suits my application's requirements, but if there existed some canonical library to take care of it, I'd rather use that :).

Answer Source

Yes, in Ruby's standard library you'll find a whole module of classes for working with URI's. There's one for HTTP. You can call #build with some arguments, much like you showed.

For the query string itself, just use Rails' Hash addition #to_query. i.e.

uri = => "", :query => { :q => "test" }.to_query)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download