One way to dynamically add attributes to some model object on the fly
is to just directly add the new key(s)/val(s) to the model instance’s
attributes:
$ ./script/console
Loading development environment (Rails 2.2.2)
test = Test.find(:first)
=> #<Test id: 1, name: “Abe”>
Another way, assuming the purpose is to add additional attribs coming
from a db qry, … Note that any additional attribs returned from a
db query will be automatically added to the returned model ob(s):
test2 = Test.find_by_sql(“select *, ‘blue’ as favorite_color from tests order by id limit 1”).first
=> #<Test id: 1, name: “Abe”>
Okay, I found a solution. It isn’t very readable, but it works:
user = User.new(:login=> “foo”, :password=>“bar”) # :password is not
a column in the db, but defined in the model using
“attr_accessor :password” (see initial post)
[:login, :password].each do |x|
getter = x # => :password
setter = (x.to_s << “=”).to_sym # => :password=
original_val = user.method(getter).call
user.method(setter).call(some_new_val)
do_some_test(user)
user.method(setter).call(original_val)
end
Thanks for the response.
I’m afraid my initial post wasn’t clear as it could be. I am trying to
find a specific syntax to access an accessor getter/setter using a
variable, in this example “x”:
user = User.new(:login=> “foo”, :password=>“bar”) # :password is not
a column in the db, but defined in the model using
“attr_accessor :password” (see initial post)
[:login, :password].each do |x|
original_val = user[x]
user[x] = some_new_val
do_some_test(user)
user[x] = original_val
end
It works for :login which is an actual attribute of User. However,
since :password was created as an attribute accessor (def password &
def password=), the syntax “user[e]” doesn’t work. I’m looking for a
way to make this work while keeping “attr_accessor :password”
I hope this is clearer.
Thanks for the assist.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.