From: Daniel Liebig Date: 2007-06-12T22:55:06+09:00 Subject: Re: assigning hash to attributes Daniel Martin wrote: > Daniel Liebig writes: > > [..] > def assign_params params > params.each { | key, value | eval "@#{key} = '#{value}'" } > end > [..] > > 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. basically i'll agree. But using the method instance_variable_set() should also fix this issue, right? Code may be passed but won't be interpreted any more, as far as i see it now. > 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}]) > => #"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. >