GET-parameters an local vars

D

Dirk Einecke

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
 
C

Ceri Storey

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

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.
 
F

Florian Gross

Dirk said:
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
 
D

Dirk Einecke

Hi Ceri,

Ceri said:
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
 
D

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top