I’m trying to DRY up a method in which I need to perform the same task on three different attributes. Like this:
if !@item.picture.blank?
picture_copy = Picture.new
picture_copy.save!
item_copy.picture = picture_copy
end
if !@item.picture_for_x.blank?
picture_for_x_copy = PictureForX.new
picture_for_x_copy.save!
item_copy.picture_for_x = picture_for_x_copy
end
if !@item.picture_for_y.blank?
picture_for_y_copy = PictureForY.new
picture_for_y_copy.save!
item_copy.picture_for_y = picture_for_y_copy
end
So basically I’m running the same code, but instantiating different objects and then assigning them to different attributes. It feels like there should be a way to DRY up this view using reflection. Is there a way that I can refer to these attributes and objects as strings passed into a helper method?
For various reasons, I can’t just use .clone or .dup: mainly because there’s binary file pointers involved and I also need deep copies.
Remember that in Ruby there are no properties or attributes available externally, just methods (which you may choose to call without parentheses so that it looks like you’re accessing a property, and which sometimes might be just returning the value of an instance variable).
Object#sendis the magic method that lets you invoke a method based on a name stored in a variable.