From: Dossy Date: 2002-05-15T19:43:56+09:00 Subject: Re: cgi params api On 2002.05.15, Patrick May wrote: > Dossy wrote in message news:<20020514172939.GL14145@panoptic.com>... > > On 2002.05.15, Wakou Aoyama wrote: > > > problem is this: > > > > > > cgi["key"].each{|value| foo(value) } > > > > > > Will this be necessary? > > > > This is my preferred idiom, personally. I don't know about > > others. > > even if you aren't looking for multiple params? Yes. Because this way the code works if there's only one value OR if there's multiple values -- I don't have to have special conditional code which I think violates OAOO and forces duplication. If I ONLY want one value regardless of if there's more than one value available, then just operating on cgi["key"] gives it to me. I don't have to worry if there's more than one value or not. If I really care to find out, I can test for multiple values by asking cgi["key"].size ... But normally, if I'm willing to tolerate multiple values at all, I don't want to have to write: if cgi.params("key").size > 1 cgi.params("key").each { |value| ... do some stuff ... } else ... do some stuff with cgi["key"] ... end This was suggested by some folks (Matz included). The premise is that more often than not, when dealing with CGI parameter values, you're dealing with a single value per key. So, making the programmer access a full array of multiple values with a new method isn't really "inconveniencing" since it's infrequent enough that it shouldn't matter. However, I think this perception is only true if you don't write a lot of CGI's -- the more you write, the more frequently you use multiple values. The trade-off is to make CGI#[] _always_ return an array of params, and do something like this: cgi["key"].each { |value| ... do some stuff for multiple values... } OR, if you only want the single value regardless: ... do some stuff with cgi["key"][0] ... However, this gets dangerous if cgi["key"] has no values and thus returns nil, NilClass#[] isn't defined, is it. So, we have to guard references to cgi["key"][0] with cgi["key"].nil? tests? Yuck. I like what I've come up with (and Wakou's code will help me improve mine) -- I'll keep it under Panoptic::CGI and use it myself, perhaps wrap cgi.rb with it. It'll certainly make writing CGI's in Ruby a lot easier for me. -- Dossy -- Dossy Shiobara mail: dossy@panoptic.com Panoptic Computer Network web: http://www.panoptic.com/ "He realized the fastest way to change is to laugh at your own folly -- then you can let go and quickly move on." (p. 70)