Dynamically calling attribute methods on ActiveRecord object

All,

I have an AR::Base descendant that has a database column named X

Given an instance obj of this object, I want to dynamically set X using

obj.send(‘X=’.to_sym, ‘value’).

I’ve done some testing with this two things present themselves:

  1. None of the AR reader methods for the attributes spring into being on
    the public interface of obj until you directly invoke one of them.

  2. The AR writer methods for the attributes never spring into being on
    the public interface of obj.

Therefore, it appears that I have to do

obj.send(‘set_attribute’, ‘X’, ‘value’)

in order to set my value.

This kind of makes sense since method_missing is really generating the
AR attribute methods.

I wonder why the reader methods show up on the public interface of obj.
I’d kind of expect that none of those “magic” methods would show up.

Sound right?

Wes

Argh. What I’ve said is wrong. I can dynamically call AR setters in
script/console.

Just not in my controller … sigh :).

Wes

Whew. Thankfully obj.send(‘X=’.to_sym, ‘value’) works fine.

Sorry for the extra chatter. Hopefully someone will have the same
doubts I did and find this useful.

WG

mvanholstyn@xena:$ ruby script/console

p=Project.new
p.send :name=, ‘mark’
p.name
=> “mark”

Works for me…


Mark Van H.
[email protected]
http://lotswholetime.com

Argh. What I’ve said is wrong. I can dynamically call AR setters in
script/console.

Just not in my controller … sigh :).

def new
@todo_list = TodoList.new
@todo_list.send :name=, ‘testing method’
end

Show up properly in my form… Again, works for me :slight_smile:

If its still a problem, post some code and maybe we can find a little
glitch
you missed.

mark


Mark Van H.
[email protected]
http://lotswholetime.com

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Wes G. wrote:

Whew. Thankfully obj.send(‘X=’.to_sym, ‘value’) works fine.

Sorry for the extra chatter. Hopefully someone will have the same
doubts I did and find this useful.

Object#send can take a String also. You don’t need the .to_sym on ‘X=’

Zach

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFE9SAhMyx0fW1d8G0RArhXAJ0Y0BapMQ3tOEki5HBLWYICkIKrkACfTKkX
KVurIXiD1NlkvFOMeEOk9e4=
=TGQm
-----END PGP SIGNATURE-----