academy

Diving into Ruby's #dup and #clone

Jeroen van Baarsen

Jeroen van Baarsen on

Diving into Ruby's #dup and #clone

In today's post, we will look into Ruby's #dup and #clone. We'll start with a real-life example that triggered this interest. After that, we'll dive deeper with the goal of learning how #dup is implemented in Ruby and how it compares to #clone. We'll then close of by implementing our own #dup method. Let's go!

How I Started Using Dup

When I worked at a company that specialized in setting up campaigns for NGO's to collect donations, I regularly had to copy campaigns and create new ones. For example, after the 2018 campaign ended, a new one for 2019 was needed.

A campaign usually had loads of configuration options, which I didn't really feel like setting up again. It would take quite some time and was error-prone. So I started by copying the DB record and went from there.

For the first few campaigns, I actually copied that by hand. It looked something like this:

1current_campaign = Campaign.find(1)
2new_campaign = current_campaign
3new_campaign.id = nil
4new_campaign.created_at = nil
5new_campaign.updated_at = nil
6new_campaign.title = "Campaign 2019"
7new_campaign.save!

This works, but requires a lot of typing, not to mention it is error-prone. I have forgotten to set the created_at to nil a few times in the past.

Since this felt like a bit of a pain, I couldn't imagine that it was the best way to go about it. And it turns out, there is a better way!

1new_campaign = Campaign.find(1).dup
2new_campaign.title = "Campaign 2019"
3new_campaign.save!

This will set the ID and the timestamps to nil, which is exactly what we want to accomplish.

This was how I first got into using #dup. Now, let's go and take a deeper look into how #dup actually works.

What Is Going on Under the Hood?

The default Ruby implementation of the #dup method allows you to add a special initializer to your object that is only called when an object is initialized via the #dup method. These methods are:

  • initialize_copy
  • initialize_dup

The implementation of these methods is actually quite interesting, as they don't do anything by default. They are basically placeholders for you to override.

This is taken directly from the Ruby source code:

1VALUE
2rb_obj_dup(VALUE obj)
3{
4    VALUE dup;
5
6    if (special_object_p(obj)) {
7            return obj;
8    }
9    dup = rb_obj_alloc(rb_obj_class(obj));
10    init_copy(dup, obj);
11    rb_funcall(dup, id_init_dup, 1, obj);
12
13    return dup;
14}

For us, the interesting part is on line 11 where Ruby calls the initializer method #intialize_dup.

The rb_funcall is a function that is used in the ruby C code a lot. It is used to call methods on an object. In this case it will call id_init_dup on the dup object. The 1 tells how many arguments there are, in this case only one: obj

Let's dive a bit deeper and look at that implementation:

1VALUE
2rb_obj_init_dup_clone(VALUE obj, VALUE orig)
3{
4    rb_funcall(obj, id_init_copy, 1, orig);
5    return obj;
6}

As you can see in this example, nothing is actually happening other than it calling id_init_copy. Now that we are down the rabbit hole, let's look at that method as well:

1VALUE
2rb_obj_init_copy(VALUE obj, VALUE orig)
3{
4    if (obj == orig) return obj;
5    rb_check_frozen(obj);
6    rb_check_trusted(obj);
7    if (TYPE(obj) != TYPE(orig) || rb_obj_class(obj) != rb_obj_class(orig)) {
8    rb_raise(rb_eTypeError, "initialize_copy should take same class object");
9    }
10    return obj;
11}

Even though there is more code, nothing special is happening except for some checks that are required internally (but that might be a good subject for another time).

So what happens in the implementation is that Ruby gives you an endpoint and provides you with the tools needed to implement your own interesting behavior.

Rails' Dup Implementation

This is exactly what Rails did in a bunch of places, but for now, we are only interested in how the id and timestamp fields get cleared.

The ID gets cleared in the core module for ActiveRecord. It takes into account what your primary key is, so even if you changed that, it will still reset it.

1# activerecord/lib/active_record/core.rb
2def initialize_dup(other) # :nodoc:
3  @attributes = @attributes.deep_dup
4  @attributes.reset(self.class.primary_key)
5
6  _run_initialize_callbacks
7
8  @new_record               = true
9  @destroyed                = false
10  @_start_transaction_state = {}
11  @transaction_state        = nil
12
13  super
14end

The timestamps are cleared in the Timestamps module. It tells Rails to clear out all the timestamps that Rails can use for creating and updating (created_at, created_on, updated_at and updated_on).

1# activerecord/lib/active_record/timestamp.rb
2def initialize_dup(other) # :nodoc:
3  super
4  clear_timestamp_attributes
5end

An interesting fact here is that Rails deliberately chose to override the #initialize_dup method instead of the #initialize_copy method. Why would it do that? Let's investigate.

Object#initialize_copy Explained

In the above code snippets, we saw how Ruby calls #initialize_dup when you use .dup on a method. But there is also an #initialize_copy method. To better explain where this is used, let's look at an example:

1class Animal
2  attr_accessor :name
3
4  def initialize_copy(*args)
5    puts "#initialize_copy is called"
6    super
7  end
8
9  def initialize_dup(*args)
10    puts "#initialize_dup is called"
11    super
12  end
13end
14
15animal = Animal.new
16animal.dup
17
18# => #initialize_dup is called
19# => #initialize_copy is called

We can now see what the calling order is. Ruby first calls out to #initialize_dup and then calls to #initialize_copy. If we would have kept the call to super out of the #initialize_dup method, we would never have called initialize_copy, so it is important to keep that in.

Are There Other Methods to Copy Something?

Now that we have seen this implementation, you might be wondering what is the use case for having two #initialize_* methods. The answer is: there is another way to copy objects, called #clone. You generally use #clone if you want to copy an object including its internal state.

This is what Rails is using with its #dup method on ActiveRecord. It uses #dup to allow you to duplicate a record without its "internal" state (id and timestamps), and leaves #clone up to Ruby to implement.

Having this extra method also asks for a specific initializer when using the #clone method. For this, you can override #initialize_clone. This method uses the same lifecycle as #initialize_dup and will call up towards #initialize_copy.

Knowing this, the naming of the initializer methods makes a bit more sense. We can use #initialize_(dup|clone) for specific implementations depending on whether you use #dup or #clone. If we have overarching behavior that is used for both, you can place it inside #initialize_copy.

Cloning an Animal

(just an example, no animals were hurt for this blog post)

Now let's look at an example of how it works in practice.

1class Animal
2  attr_accessor :name, :dna, :age
3
4  def initialize
5    self.dna = generate_dna
6  end
7
8  def initialize_copy(original_animal)
9    self.age = 0
10    super
11  end
12
13  def initialize_dup(original_animal)
14    self.dna = generate_dna
15    self.name = "A new name"
16    super
17  end
18
19  def initialize_clone(original_animal)
20    self.name = "#{original_animal.name} 2"
21    super
22  end
23
24  def generate_dna
25    SecureRandom.hex
26  end
27end
28
29bello = Animal.new
30bello.name = "Bello"
31bello.age = 10
32
33bello_clone = bello.clone
34bello_dup = bello.dup
35
36bello_clone.name # => "Bello 2"
37bello_clone.age # => 0
38
39bello_dup.name # => "A new name"
40bello_dup.age # => 0

Let's break down what is actually happening here. We have a class called Animal, and depending on how we copy the animal, it should have different behavior:

  • When we clone the animal, the DNA remains the same, and its name will be the original name with 2 appended to it.
  • When we duplicate the animal, we make a new animal based on the original one. It gets its own DNA and a new name.
  • In all cases the animal starts as a baby.

We implemented three different initializers to make this happen. The #initialize_(dup|clone) method will always call up to #initialize_copy, thus ensuring that the age is set to 0.

Rounding up the CLONES and Other Animals

Starting by explaining the itch we needed to scratch ourselves, we looked into copying a database record. We went from copying by hand in the Campaign example, to #dup and #clone. We then took it from the practical to the fascinating and looked into how this is implemented in Ruby. We also played around with #cloneing and #duping animals. We hope you enjoyed our deep dive as much as we did writing it.

Share this article

RSS

AppSignal monitors your apps

AppSignal provides insights for Ruby, Rails, Elixir, Phoenix, Node.js, Express and many other frameworks and libraries. We are located in beautiful Amsterdam. We love stroopwafels. If you do too, let us know. We might send you some!

Discover AppSignal
AppSignal monitors your apps