Re: [NYC-rb] Rails 3.1 Active Record dup

From: Joshua B.
Sent on: Thursday, November 17, 2011 11:27 AM
Hey Robert,

There's an old trick in Ruby to "unfreeze" an object without triggering #initialize_dup:

> obj = Marshal.load(Marshal.dump(obj))

The problem, of course, is that Marshaling is not exactly fast. If this is something that you will be doing frequently, you may prefer to monkey-patch AR.

- Josh

On Thursday, November 17, 2011 at 10:47 AM, Robert Beene wrote:

Hey all,

I'm working on a Rails 3.1 project that makes use of memcached (using dalli_store) in various spots. When caching a specific instance of a model, I will cache the entire object and update it accordingly with after_save callbacks. The problem is that items pulled from cache are frozen. Normally, I would use the dup method but in Rails 3.1.0, this method was updated. 

In Rails 3.0.9, all the attributes were simply copied over (source). In Rails 3.1.0, another method is called (initialize_dup) that does much more (source). Comments on that method below:

      # Duped objects have no id assigned and are treated as new records. Note
      # that this is a "shallow" copy as it copies the object's attributes
      # only, not its associations. The extent of a "deep" copy is application
      # specific and is therefore left to the application to implement according
      # to its need.
      # The dup method does not preserve the timestamps (created|updated)_(at|on).

As this object may be updated/destroyed, dup in 3.1.0 world doesn't fit the bill as primary key is removed.

Clone keeps everything including the frozen state of the object. 

I imagine the reasoning here is that AR is attempting to prevent updating an object in the db based on a potentially out of date cache copy. I'm considering cracking open AR and commenting out the lines in initialize_dup that are preventing this from working. 

Thoughts? Alternatives?

- Robert

Please Note: If you hit "REPLY", your message will be sent to everyone on this mailing list ([address removed])
This message was sent by Robert Beene ([address removed]) from NYC.rb.
To learn more about Robert Beene, visit his/her member profile
To unsubscribe or to update your mailing list settings, click here

Meetup, PO Box 4668 #37895 New York, New York[masked] | [address removed]

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy