I use eval() in an initialize method:
class ActiveRecord::FakedModel
def initialize(attributes={})
attributes = {} if not attributes
attributes.each do |attr_name, value|
eval("@#{attr_name}=#{value.inspect}")
end
@attributes = attributes
end
...
end
and have a setter for cleaning whitespaces:
class ContactForm < ActiveRecord::FakedModel
attr_accessor :plz
def plz=(plz)
@plz = plz.try(:delete,' ')
end
...
end
but this setter doesn’t work when I give ‘plz’ in a hash:
c=ContactForm.new(:plz=>' 1 3 3 3 ')
=> #<ContactForm:0x1024e3a10 @attributes={:plz=>" 1 3 3 3 "}, @plz=" 1 3 3 3 ">
Is there anything wrong with using setters in eval?
Your eval statement is not calling the setter method, it is setting the instance variable directly. If you want your constructor to use the setter, use send: