Synthesis : Scott Becker

Hash – to_query

Look what just appeared in Rails trunk – Hash#to_query – turn a hash of values into a form-encoded query string. I’ve wanted this on occasion in the past. Check it out:

Simple Conversion

{:a => 10}.to_query

Becomes this:


Nested Conversion

{:person => {:name => 'Nicholas', :login => 'seckar'}}.to_query

Becomes this:


Multiple Nested

{:person => {:id => 10}, :account => {:person => {:id => 20}}}.to_query

Becomes this:


Array Values

{:person => {:id => [10, 20]}}.to_query

Becomes this:


You can do the same thing in Prototype:

$H({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' }).toQueryString();

Becomes this:


It doesn’t look like Prototype handles the nested conversions yet though.


Comments are closed.