GET-parameters an local vars

Hi.

I call i a file like this: index.rb?foo=test1&bar=test2
Now I want all given parameters as local vars:

foo = cgi.params[‘foo’][0]
bar = cgi.params[‘bar’][0]

Is there a faster way for example with a loop to write all given
parameters in local vars?

greetings
Dirk Einecke

Well, you could do something with eval allong the following lines, but
It’s a rather Bad Idea.

def setup(params, binding)
params.each do |key, val|
eval(“%s = %s” % [key, val[0]], binding)
end
end

the call to Kernel#binding method is the key here, since it allows you

to assign to the variables within the correct scope.

setup(cgi.params, binding)

A cleaner solution might well be to use a proxy object, which makes use
of the special method, method_missing to map keys to values.

class CgiParam
def initialize(params)
@params = params
end
def method_missing(m, *other)
@params[m.to_s][0]
end
end

p = CgiParam.new(cgi.params)

… if (p.foo) # do things
… unless (p.bar.to_i) # other things

Although there may still be a better way of doing it.

···

On Sun, May 16, 2004 at 04:03:50AM +0900, Dirk Einecke wrote:

Hi.

Is there a faster way for example with a loop to write all given
parameters in local vars?


Ceri Storey cez@necrofish.org.uk

Dirk Einecke wrote:

Hi.

Moin!

Is there a faster way for example with a loop to write all given
parameters in local vars?

This code might help:

arg = Module.new do
extend self
define_method(:method_missing) do |name|
(cgi.params[name.to_s] || ).first
end
end

It’s used like this:

arg.one # => ‘eins’
arg::two # => ‘zwei’

You can even do this if you want PHP-style auto import, but I heavily
suggest not doing this: (Huge security traps are caused by it!)

include arg
three # => ‘drei’

greetings
Dirk Einecke

Regards,
Florian Gross

Hi Ceri,

Ceri Storey wrote:

A cleaner solution might well be to use a proxy object, which makes use
of the special method, method_missing to map keys to values.

class CgiParam
def initialize(params)
@params = params
end
def method_missing(m, *other)
@params[m.to_s][0]
end
end

p = CgiParam.new(cgi.params)

. if (p.foo) # do things
… unless (p.bar.to_i) # other things

This sounds good. I will try this…
Thanks.

greetings
Dirk Einecke

Hi Florian,

Thank you for you posting. Sound good too - but first I will try the way
Ceri shows with the class.

greetings (to germany?)
Dirk Einecke (from germany - Karlsruhe)