Skip to content

Extends the functionality of ActiveRecord::Base#clone to perform a deep clone that includes user specified associations.

License

Notifications You must be signed in to change notification settings

liveline/deep_cloneable

 
 

Repository files navigation

Deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone. It is a rails3 upgrade of the deep_cloning plugin (github.com/openminds/deep_cloning).

Requirements

  • Activerecord 3.1, 3.2

  • Rails 2.x/3.0 users, please check out the ‘rails2.x-3.0’ branch.

Installation

  • In your Gemfile:

    gem ‘deep_cloneable’, ‘~> 1.4.0’

Example

Cloning one single association

pirate.dup :include => :mateys

Cloning multiple associations

pirate.dup :include => [:mateys, :treasures]

Cloning really deep

pirate.dup :include => {:treasures => :gold_pieces}

Cloning really deep with multiple associations

pirate.dup :include => [:mateys, {:treasures => :gold_pieces}]

Cloning really deep with multiple associations and a dictionary

A dictionary ensures that models are not cloned multiple times when it is associated to nested models. When using a dictionary, ensure recurring associations are cloned first:

pirate.dup :include => [:mateys, {:treasures => [:matey, :gold_pieces], :use_dictionary => true }]

If this is not an option for you, it is also possible to populate the dictionary manually in advance:

dict = { :mateys => {} }
pirate.mateys.each{|m| dict[:mateys][m] = m.dup }
pirate.dup :include => [:mateys, {:treasures => [:matey, :gold_pieces], :dictionary => dict }]

Cloning a model without an attribute

pirate.dup :except => :name

Cloning a model without multiple attributes

pirate.dup :except => [:name, :nick_name]

Cloning a model without an attribute or nested multiple attributes

pirate.dup :include => :parrot, :except => [:name, { :parrot => [:name] }]

Cloning with a block

pirate.dup :include => :parrot do |original, kopy|
  kopy.cloned_from_id = original.id if kopy.respond_to?(:cloned_from_id)
end

Contributors

  • Michael He

  • Indrek Juhkam

  • Mart Karu

  • Rolf Timmermans

  • Ilya Kuzmin

  • zozi

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Copyright © 2012 Reinier de Lange. See LICENSE for details.

About

Extends the functionality of ActiveRecord::Base#clone to perform a deep clone that includes user specified associations.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 100.0%