Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 通过字符串引用对象属性_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 通过字符串引用对象属性

Ruby on rails 通过字符串引用对象属性,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试一种方法,在这种方法中,我需要在三个不同的属性上执行相同的任务。像这样: 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.sa

我正在尝试一种方法,在这种方法中,我需要在三个不同的属性上执行相同的任务。像这样:

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
所以基本上我运行相同的代码,但是实例化不同的对象,然后将它们分配给不同的属性。感觉应该有一种方法可以通过反射来消除这种观点。有没有一种方法可以将这些属性和对象引用为传递到helper方法中的字符串

出于各种原因,我不能只使用.clone或.dup:主要是因为涉及到二进制文件指针,而且我还需要深度拷贝

{
  picture:       Picture,
  picture_for_x: PictureForX,
  picture_for_y: PictureForY
}.each do |name,klass|
  if !@item.send(name).blank?
    copy = klass.new
    copy.save!
    item_copy.send("#{name}=",copy)
  end
end
请记住,在Ruby中,外部没有可用的属性或属性,只有方法(您可以选择在不带括号的情况下调用这些方法,以便看起来您正在访问属性,有时可能只是返回实例变量的值)

是一种神奇的方法,它允许您根据存储在变量中的名称调用方法

def picture_for_x_blank?(s = "")
  s = "_for_#{s}" unless s.empty?
  m = "picture#{s}"

  unless @item.send(m).blank?
    copy = Kernel::const_get(m.camelize).new
    copy.save!
    item_copy.send("#{m}=", copy)
  end
end

picture_for_x_blank?
picture_for_x_blank?("x")
picture_for_x_blank?("y")