Daniel Liebig <daniel.liebig@wevin.de> writes:
What i'm trying this time is to pass a hash of parameters (passed by a
HTML form i.e.) to an new Object and then automatically assign the
values of this hash to the attributes of that object named like the
keys of that hash.
Well, your initial attempt made all my internal security alarms go
"ACK!" - since a web user can pass pretty much arbitrary name/value
pairs in, that code lets a malicious user execute arbitrary ruby code
on your system by passing in a specially crafted name.
How are you intending to use this object? You might find something
like this more useful:
class HashAttrib
def initialize(parms={})
@parameters=parms
end
def method_missing(sym, *args)
return @parameters[sym.to_s] if args.empty?
if sym.to_s =~ /=$/ and args.size == 1 then
return @parameters[sym.to_s[0..-2]] = args[0]
end
return super.method_missing(sym, *args)
end
end
Then, here's how you can use this class:
irb(main):013:0> a = HashAttrib.new(Hash[*%w{color red string 1 jump yes}])
=> #<HashAttrib:0xb7c013b0 @parameters={"jump"=>"yes", "color"=>"red",
"string"=>"1"}>
irb(main):014:0> a.jump
=> "yes"
irb(main):015:0> a.color
=> "red"
irb(main):016:0> a.string
=> "1"
irb(main):017:0> a.colour
=> nil
irb(main):018:0> a.colour=a.color
=> "red"
irb(main):019:0> a.colour
=> "red"
Now, this doesn't make the attributes (which is the word you seem to
be using for instance variables) equal to what's in the hash, really,
it just fakes attributes by turning a.whatever into a hash lookup for
"whatever" in @parameters.
You might want to consider also adding an attr_accessor declaration
for "parameters" to HashAttrib to let you get at the underlying hash.
···
--
s=%q( Daniel Martin -- martin@snowplow.org
puts "s=%q(#{s})",s.to_a.last )
puts "s=%q(#{s})",s.to_a.last