[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Building querystrings with ruby

ngw

3/15/2006 12:23:00 AM

Hi *, my question is really simple: is there a way in Ruby stdlib or in
external modules to build querystrings without creating the string from
scratch ?
For example something like:

name = "Foo Bar"
p URI::join(base_uri, query_string(name))

-> "http://foobar.org/?name=Foo...

Obviously this code is totally invented.
If not (haven't found anything in the documentation) how does people
accomplish this task ?

TIA,
ngw
7 Answers

Ara.T.Howard

3/15/2006 2:33:00 AM

0

Paul Battley

3/15/2006 9:07:00 AM

0

On 15/03/06, ara.t.howard@noaa.gov <ara.t.howard@noaa.gov> wrote:
> require "cgi"
> class Hash
> def query_string
> "?" << inject([]){|a,kv| a << [CGI.escape(kv.shift), CGI.escape(kvshift)].join("=") }.join("&")
> end
> end

Now here's somewhere I can use the handy trick I learned yesterday:

"?" << inject([]){ |a,(k,v)| a << [CGI.escape(k),
CGI.escape(v)].join("=") }.join("&")

But this is shorter:

"?" << inject([]){ |a,kv| a << kv.map{ |e| CGI.escape(e) }.join("=") }.join("&")

And this is shorter still:

"?" << to_hash.map{ |kv| kv.map{ |e| CGI.escape(e) }.join("=") }.join("&")

Paul.


Paul Battley

3/15/2006 9:09:00 AM

0

On 15/03/06, Paul Battley <pbattley@gmail.com> wrote:
> And this is shorter still:
>
> "?" << to_hash.map{ |kv| kv.map{ |e| CGI.escape(e) }.join("=") }.join("&")

Ignore my stupidity above; this is shorter and less redundant:

"?" << map{ |kv| kv.map{ |e| CGI.escape(e) }.join("=") }.join("&")

Paul.


ngw

3/15/2006 10:14:00 AM

0

-Paul Battley <pbattley@gmail.com>:
> On 15/03/06, Paul Battley <pbattley@gmail.com> wrote:
>> And this is shorter still:
>>
>> "?" << to_hash.map{ |kv| kv.map{ |e| CGI.escape(e) }.join("=") }.join("&")
>
> Ignore my stupidity above; this is shorter and less redundant:
>
> "?" << map{ |kv| kv.map{ |e| CGI.escape(e) }.join("=") }.join("&")

Wow !
Thank you both, great snippets.

ngw

ebeard

3/16/2006 2:07:00 PM

0

Wow, I have no idea what this does or how it works. Would you mind
taking this apart and describing how it works?

Paul Battley

3/16/2006 4:27:00 PM

0

On 16/03/06, ebeard <ecbearden@gmail.com> wrote:
> Wow, I have no idea what this does or how it works. Would you mind
> taking this apart and describing how it works?

"?"<<map{|h|h.map{|e|CGI.escape(e)}*'='}*'&'

This can be spaced out a bit:

"?" << # append what follows to the string '?'
map { |h| # h looks like ['key', 'value'] for each key-value pair
h.map { |e| # e looks like 'key' or 'value'
CGI.escape(e) # escape each element
} * '=' # join key and value with '='
} * '&' # join each key-value pair with '&'

Is that any clearer?

Paul.


ebeard

3/22/2006 3:31:00 PM

0

perfectly. very clever.

thanks,

chad.