0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ActiveModelで生成したオブジェクトのdeep copy

Posted at

やりたいこと

タイトルのまま。ActiveModel::Modelで生成したオブジェクトをattribute含めて全て別のオブジェクトとして複製したい。

ActiveSupportのdeep_dupを試してみた

結論を書くとattributeまで複製されなかったので失敗。

class Test
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :age, :integer
end

original = Test.new(name: "Abe", age: 65)
clone = original.deep_dup

# 表面のオブジェクトは別物が生成
original.object_id # => 33487180
clone.object_id    # => 33536560

# でも属性は同じものを指している
original.name.object_id # => 33576180
clone.name.object_id    # => 33576180

Marshalしかないのか

オブジェクトの中身を全てダンプで吐き出して、それを再オブジェクト化するというワザ。これなら要素も複製できた。

original = Test.new(name: "Abe", age: 65)
clone = Marshal.load(Marshal.dump(original))

# 要素も異なるオブジェクトIDになっている。
original.name.object_id # => 34629860
clone.name.object_id    # => 34628880

他に方法があれば誰か教えて下さいm(_ _)m

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?