Simple copy of attributes

V

Vincent Fourmond

Hello !

I've just stumbled upon code where you have different classes with no
relations, and that you want to copy some attributes from one to the
other. So I came up with this:

def copy_attributes(dest, src, *attrs)
for attr in attrs
dest.send(attr.to_s + '=',src.send(attr))
end
end

Then, if you want, say, to copy the attributes foo, bar and baz (to
reach summits in originality) from biniou to bidule you just need:

copy_attributes(bidule, biniou, :foo, :bar, :baz)

Is there already a function from standard libs doing something similar ?

I know that some of you will answer that coming to such a need means I
should probably refactor my code. Well, as in my case I need to copy
similar members from quite different Struct, I would say no ;-)... (and
it's a 100-lines script, not a big project !).

Cheers !

Vince
 
V

Vincent Fourmond

Paul said:
My personal view is that you should create a class responsible for data
handling and processing, and include methods capable of cloning some or all
of the data members of one instance of the class to another. That way, you
will have encapsulated the specifics of the data copying or processing
within the class.

I agree that that would be the Ruby OO way. But, let's face it, for
small scripts, a script-like procedural approach is much faster and
easier to develop. For one, I discovered I would use another class just
about when I reached the line where it became necessary...

Vince
 
T

Trans

Vincent said:
Hello !

I've just stumbled upon code where you have different classes with no
relations, and that you want to copy some attributes from one to the
other. So I came up with this:

def copy_attributes(dest, src, *attrs)
for attr in attrs
dest.send(attr.to_s + '=',src.send(attr))
end
end

Then, if you want, say, to copy the attributes foo, bar and baz (to
reach summits in originality) from biniou to bidule you just need:

copy_attributes(bidule, biniou, :foo, :bar, :baz)

Is there already a function from standard libs doing something similar ?

I know that some of you will answer that coming to such a need means I
should probably refactor my code. Well, as in my case I need to copy
similar members from quite different Struct, I would say no ;-)... (and
it's a 100-lines script, not a big project !).

Facets has Kernel#set_from:

bidule.set_from(biniou, :foo, :bar, :baz)

hth,
t.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top