From 8ac17e6d9bcb89230919bd3cb9e2f52303a07612 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 13 Jun 2009 15:37:59 +0200 Subject: AS guide: explains to_query --- .../guides/source/active_support_overview.textile | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'railties/guides/source/active_support_overview.textile') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index d45aff81a0..aeaebe140e 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -138,6 +138,53 @@ user_path(@user) # => "/users/357-john-smith" WARNING. Controllers need to be aware of any redifinition of +to_param+ because when a request like that comes in "357-john-smith" is the value of +params[:id]+. +h4. +to_query+ + +Except for hashes, given an unescaped +key+ this method constructs the part of a query string that would map such key to what +to_param+ returns. For example, given + + +class User + def to_param + "#{id}-#{name.parameterize}" + end +end + + +we get: + + +current_user.to_query('user') # => user=357-john-smith + + +This method escapes whatever is needed, both for the key and the value: + + +u.to_query('company[name]') +# => "company%5Bname%5D=Johnson+%26+Johnson" + + +so its output is ready to be used in a query string. + +Arrays return the result of applying +to_query+ to each element with _key_[] as key, and join the result with "/": + + +[3.4, -45.6].to_query('sample') +# => "sample%5B%5D=3.4&sample%5B%5D=-45.6" + + +Hashes also respond to +to_query+ but with a different signature. If no argument is passed a call generates a sorted series of key/value assigments calling +to_query(key)+ on its values. Then it joins the result with "&": + + +{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3" + + +The method +Hash#to_query+ accepts an optional namespace for the keys: + + +{:id => 89, :name => "John Smith"}.to_query('user') +# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith" + + h3. Extensions to +Module+ ... -- cgit v1.2.3