我想用来value.respond_to?(:dup) ? value.dup : value检查我是否可以复制一个对象,但它失败了,TypeError在booleans,nil或类似的"原语"上.
我最终得到了:
begin
value = value.dup
rescue
#ignore, use the original if no dup-able (e.g nil, true, etc)
end
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
额外奖励:为什么会回应:dup?
不深dup,仅针对这个问题.
编辑:思考:
obj.class.methods.include? :new 很好,但有点过于hackish我觉得它有糟糕的表现 Marshal 看起来也有点矫枉过正dup在对象级别定义是错误的.所以,引用@Linuxios
没有更好的方法
创建记录后,我会发送一封电子邮件,这是在after_commit回调中执行的。我想将Message-Id电子邮件的标题保存为记录上的属性以供以后使用。我将其实现为:
after_commit on: :create do
if email = Mailer.email(self).deliver
# `self.message_id = email.message_id` has no effect, so I'm calling update()
self.update message_id: email.message_id
end
end
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是(对我来说),这会导致无限的电子邮件发送循环(对不起,Mailgun);看来即使on: :create指定了回调也会在更新时调用。
这种方法有什么我没有看到的问题吗?我还能如何将此值附加到此记录中?
我唯一的想法是尝试对 上的回调进行门控previous_changes,但无论如何我想了解为什么这不能按原样工作。