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:

a=10

Nested Conversion

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

Becomes this:

person[name]=Nicholas&person[login]=seckar

Multiple Nested

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

Becomes this:

account[person][id]=20&person[id]=10

Array Values

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

Becomes this:

person[id][]=10&person[id][]=20

You can do the same thing in Prototype:

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

Becomes this:

'action=ship&order_id=123&fees=f1&fees=f2&label=a%20demo'

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

 

Comments are closed.