SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Inverse of CGI.parse

    CGI.parse takes a querystring and returns a hash. I'm looking for a way to do the inverse. Any suggestions?

  2. #2
    SitePoint Addict
    Join Date
    Feb 2007
    Posts
    270
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    given "hash" as a hash, try hash.to_query and see if that's what you're looking for.

  3. #3
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Close, but not quite. CGI.parse gives back an array of values, even when there is just one. to_query interprets this as the value being present multiple times. I just wrote my own implementation, but if a standard solution existed, I would have preferred to use that.

  4. #4
    SitePoint Guru Majglow's Avatar
    Join Date
    Aug 1999
    Location
    B-Town
    Posts
    645
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    my_hash.map { |key, value| "#{key}=#{CGI.escape(value)}" }.join('&')
    Ohai!

  5. #5
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Not quite. The result from CGI.parse looks like this:
    Code:
    irb(main):002:0> CGI.parse "foo=42&bar[]=1&bar[]=2&bar[]=3"
    => {"bar[]"=>["1", "2", "3"], "foo"=>["42"]}
    Which does make sense, but also means that the serialization code becomes a bit more tricky. Anyway, I figured it out - it's just that if some kind of standard function existed, I would rather have used that.

  6. #6
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just in case somebody else needs this, here's the code I came up with:

    Code:
    require 'uri'
    def hash_to_query(h)
      h.map do |k, v|
        v.map do |value|
          (value.nil?) ? URI.encode(k.to_s) : "%s=%s" % [URI.encode(k.to_s), URI.encode(value.to_s)]
        end
      end.flatten.join("&")
    end


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •