From: Justin White Date: 2003-03-18T14:22:47+09:00 Subject: Parsing a CGI query (Re: Your favorite Ruby web library?) On Sunday, March 16, 2003, at 07:08 , Eric Hodel wrote: > Provided you can run a CGI, Borges should work. If you're not using > mod_ruby, you'll have to figure out how to grab the GET and POST args > yourself, because I've not puzzled that out yet. i have. i'll put it down here, for you and to make sure i actually know what i'm doing (check my sanity fellow Rubyists :P ) CGI data is stored in environment variables passed to the CGI executable. use Ruby's global ENV Hash to retrieve them. ENV['REQUEST_METHOD'] is GET or POST. for GET requests, ENV['QUERY_STRING'] is the string after the question mark in the URL. for example: cgi.rb?key=val;foo=bar QUERY_STRING = 'key=val;foo=bar' split QUERY_STRING on ';' or '&'. i use semicolons because it doesn't affect URL encoding routines like an ampersand might, but my scripts check for & just in case. they're both valid as far as i know. then split each element on '=' to get your keys and values. a very simple GET query parser could look like this: ## CGI GET query parser params = {} ENV['QUERY_STRING'].split(/[;&]/).each { |pair| key, val = pair.split(/=/) params[key] = val } ## end note that this simple parser will overwrite repeated keys, which is not standards compliant. Ruby's cgi.rb always puts them in an Array to be safe (params[key].push val). ask me or see Perl5's CGI.pl for another way to deal with it. (my way is Perl5's in Ruby :P ) extra: PATH_INFO is also filled in, if the script name is followed by a / and some text in the request URL. PATH_TRANSLATED is PATH_INFO appended to the httpd's DocumentRoot. following the path with an optional question mark can create a QUERY_STRING as well as the PATH_INFO. for example: cgi.rb/foo/bar?key=val PATH_INFO = '/foo/bar' QUERY_STRING = 'key=val' i haven't done any POST work yet, but i believe it's mostly the same, with some checking of CONTENT_LENGTH and such to ensure you have the data you want. happy hacking! -Justin White just6979@yahoo.com http://tin.2y.net/ AIM: just6979