Dynamic methods for copying objects

Hi,

I was wondering if this is possible.

dyn_method = "roles"
Object1 = User.find(1)
object2 = User.find(2)

object1.dyn_method = object2.dyn_method

So what im going to have is a load of strings coming in which are
related to the object and i want to copy everything from object2 to
object1 in the case above. Im going to be doing this several times for
different methods related so i would rather one method to this and i
just tell it what method and pass the objects.

dyn_method = "addresses"

object1.dyn_method = object2.dyn_method

Ive tried various things like:

dyn_method = "roles".to_syn

object1.send(dyn_method, object2.dyn_method)

Anyone got any ideas?

JB

Hi,

I was wondering if this is possible.

dyn_method = "addresses"

object1.dyn_method = object2.dyn_method

object2.send(dyn_method) will get you back the expected value. The key
fact here are
  - that an accessor is a pair of methods: a reader and a writer
  - a.b corresponds to calling the method b
  - a.b = c correspons to calling the method b=, with parameter c.

Armed with this it should be obvious: object1.send(dyn_method + '=',
object2.send(dyn_method))

Fred

Frederick Cheung wrote:

Hi,

I was wondering if this is possible.

dyn_method = "addresses"

object1.dyn_method = object2.dyn_method

object2.send(dyn_method) will get you back the expected value. The key
fact here are
  - that an accessor is a pair of methods: a reader and a writer
  - a.b corresponds to calling the method b
  - a.b = c correspons to calling the method b=, with parameter c.

Armed with this it should be obvious: object1.send(dyn_method + '=',
object2.send(dyn_method))

Fred

ok thanks, i see where your coming from now. If object1 already had 2
roles would it be possible to add more objects. So if object1 had 2
roles already i will have to check for different roles that object2 has
and add any different ones. The above line of code overwrites the
exisiting roles with the roles that object 2 has.

newrole = role.find(:first)

object1.send(dyn_method + '<<', newrole)

??

JB

Fred

ok thanks, i see where your coming from now. If object1 already had 2
roles would it be possible to add more objects. So if object1 had 2
roles already i will have to check for different roles that object2
has
and add any different ones. The above line of code overwrites the
exisiting roles with the roles that object 2 has.

newrole = role.find(:first)

object1.send(dyn_method + '<<', newrole)

It doesn't go that far : there is no foo<< method (but if you're
looking at hashes/arrays etc... there is [] and []=
I suppose this is because with << you aren't assigning a new
collection, you are mutating an existing one.
So for this, object1.send(dynmethod) << newrole would do the trick

Fred