{"id":13427735,"url":"https://github.com/moiristo/deep_cloneable","last_synced_at":"2025-05-13T19:10:18.959Z","repository":{"id":1125851,"uuid":"999967","full_name":"moiristo/deep_cloneable","owner":"moiristo","description":"This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.","archived":false,"fork":false,"pushed_at":"2025-02-03T09:17:52.000Z","size":283,"stargazers_count":799,"open_issues_count":8,"forks_count":90,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-04-27T04:53:58.674Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/moiristo.png","metadata":{"files":{"readme":"readme.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2010-10-18T18:49:54.000Z","updated_at":"2025-04-26T15:36:23.000Z","dependencies_parsed_at":"2022-07-08T01:31:00.604Z","dependency_job_id":"4990eccb-c2fe-4337-bf1d-a4f0ddbb2e44","html_url":"https://github.com/moiristo/deep_cloneable","commit_stats":{"total_commits":216,"total_committers":33,"mean_commits":6.545454545454546,"dds":0.4629629629629629,"last_synced_commit":"647c996f5954eac1e13347e871bded21c758572e"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moiristo%2Fdeep_cloneable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moiristo%2Fdeep_cloneable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moiristo%2Fdeep_cloneable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moiristo%2Fdeep_cloneable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/moiristo","download_url":"https://codeload.github.com/moiristo/deep_cloneable/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251089605,"owners_count":21534518,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T01:00:39.542Z","updated_at":"2025-04-27T04:54:04.237Z","avatar_url":"https://github.com/moiristo.png","language":"Ruby","readme":"# deep_cloneable\n\n![Build Status](https://github.com/moiristo/deep_cloneable/actions/workflows/ruby.yml/badge.svg)\n\nThis gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations. It is a rails 3+ upgrade of the [deep_cloning plugin](http://github.com/openminds/deep_cloning).\n\n## Requirements\n\n- Ruby 2.3.0, 2.4.4, 2.5.5, 2.6.3, 2.7.5, 3.3.5 (tested)\n- Activerecord 3.2, 4.0, 4.1, 4.2, 5.0, 5.1, 5.2, 6.0, 7.0, 8.0 (tested)\n- Rails 2.x/3.0 users, please check out the 'rails2.x-3.0' branch\n\n## Installation\n\n- Add deep_cloneable to your Gemfile:\n\n```ruby\ngem 'deep_cloneable', '~\u003e 3.2.1'\n```\n\n## Upgrade details\n\n### Upgrading from v2\n\nThere are two breaking changes that you might need to pay attention to:\n\n- When using an optional block (see below), the block used to be evaluated before `deep_cloneable` had performed its changes (inclusions, exclusions, includes). In v3, the block is evaluated after all processing has been done, just before the copy is about to be returned.\n- When a defined association is not found, `deep_cloneable` raises an exception. The exception class has changed namespace: the class definition used to be `ActiveRecord::Base::DeepCloneable::AssociationNotFoundException` and this has changed to `DeepCloneable::AssociationNotFoundException`.\n\n### Upgrading from v1\n\nThe `dup` method with arguments has been replaced in deep_cloneable 2 by the method `deep_clone`. Please update your sources accordingly.\n\n## Usage\n\nThe `deep_clone` method supports a couple options that can be specified by passing an options hash. Without options, the behaviour is the same as ActiveRecord's [`dup`](http://apidock.com/rails/ActiveRecord/Core/dup) method.\n\n### Association inclusion\n\nAssociations to be included in the dup can be specified with the `include` option:\n\n```ruby\n# Single include\npirate.deep_clone include: :mateys\n\n# Multiple includes\npirate.deep_clone include: [ :mateys, :treasures ]\n\n# Deep includes\npirate.deep_clone include: { treasures: :gold_pieces }\npirate.deep_clone include: [ :mateys, { treasures: :gold_pieces } ]\n\n# Disable validation for a performance speedup when saving the dup\npirate.deep_clone include: { treasures: :gold_pieces }, validate: false\n\n# Conditional includes\npirate.deep_clone include: [\n  {\n    treasures: { gold_pieces: { if: lambda{|piece| piece.is_a?(Parrot) } } } },\n    mateys: { unless: lambda{|matey| matey.is_a?(GoldPiece) }\n  }\n]\n\nship.deep_clone include: [\n  pirates: [ :treasures, :mateys, if: lambda {|pirate| pirate.name == 'Jack Sparrow' } ]\n]\n```\n\n#### The Dictionary (Object Reusage)\n\nThe dictionary ensures that models are not duped multiple times when it is associated to nested models. It does this by storing a mapping of the original object to its duped object. It can be used as follows:\n\n```ruby\n# Enables the dictionary (empty on initialization)\npirate.deep_clone include: [ :mateys, { treasures:  [ :matey, :gold_pieces ] } ], use_dictionary: true\n\n# Deep clones with a prefilled dictionary\ndictionary = { mateys: {} }\npirate.mateys.each{|m| dict[:mateys][m] = m.deep_clone }\npirate.deep_clone include: [ :mateys, { treasures: [ :matey, :gold_pieces ] } ], dictionary: dictionary\n```\n\n### Attribute Exceptions \u0026 Inclusions\n\nThe `deep_clone` method supports both `except` and `only` for specifying which attributes should be duped:\n\n#### Exceptions\n\n```ruby\n# Single exception\npirate.deep_clone except: :name\n\n# Multiple exceptions\npirate.deep_clone except: [ :name, :nick_name ]\n\n# Nested exceptions\npirate.deep_clone include: :parrot, except: [ :name, { parrot: [ :name ] } ]\n```\n\n#### Inclusions\n\n```ruby\n# Single attribute inclusion\npirate.deep_clone only: :name\n\n# Multiple attribute inclusions\npirate.deep_clone only: [ :name, :nick_name ]\n\n# Nested attribute inclusions\npirate.deep_clone include: :parrot, only: [ :name, { parrot: [ :name ] } ]\n\n```\n\n### Pre- and postprocessor\n\nYou can specify a pre- and/or a postprocessor to modify a duped object after duplication:\n\n```ruby\npirate.deep_clone(include: :parrot, preprocessor: -\u003e(original, kopy) { kopy.cloned_from_id = original.id if kopy.respond_to?(:cloned_from_id) })\npirate.deep_clone(include: :parrot, postprocessor: -\u003e(original, kopy) { kopy.cloned_from_id = original.id if kopy.respond_to?(:cloned_from_id) })\n```\n\n_Note_: Specifying a postprocessor is essentially the same as specifying an optional block (see below).\n\n_Note_: Using `deep_clone` with a processors will pass all associated objects that are being cloned to the processor, so be sure to check whether the object actually responds to your method of choice.\n\n### Optional Block\n\nPass a block to `deep_clone` to modify a duped object after duplication:\n\n```ruby\npirate.deep_clone include: :parrot do |original, kopy|\n  kopy.cloned_from_id = original.id if kopy.respond_to?(:cloned_from_id)\nend\n```\n\n_Note_: Using `deep_clone` with a block will also pass the associated objects that are being cloned to the block, so be sure to check whether the object actually responds to your method of choice.\n\n### Cloning models with files\n\n#### Carrierwave\n\nIf you are cloning models that have associated files through Carrierwave these will not get transferred automatically. To overcome the issue you need to explicitly set the file attribute.\n\nEasiest solution is to add the code in a clone block as described above.\n\n```ruby\npirate.deep_clone include: :parrot do |original, kopy|\n  kopy.thumbnail = original.thumbnail\nend\n```\n\n#### Shrine\n\nShrine is similar to Carrierwave, but you have to clear the `image_data` hash attribute from the copy, otherwise Shrine will think there's an old attachment to clean up and will delete the original image.\n\n```ruby\npirate.deep_clone include: [:photos, :parrot] do |original, kopy|\n  if kopy.is_a?(Photo)\n    kopy.image_data = nil\n    kopy.image = original.image\n  end\nend\n```\n\nNote you're not assigning `image_data` directly, otherwise this would result in both records sharing the same asset in your storage.\n\nDirectly assigning `kopy.image` to `original.image` ensures you use your usual uploading mechanism, such as background jobs.\n\n#### ActiveStorage\n\nFor ActiveStorage, you have two options: you can either make a full copy, or share data blobs between two records.\n\n##### Full copy example\n\n```ruby\n# Rails 5.2, has_one_attached example 1\npirate.deep_clone include: [:parrot, :avatar_attachment, :avatar_blob]\n\n# Rails 5.2, has_one_attached example 2\npirate.deep_clone include: :parrot do |original, kopy|\n  if kopy.is_a?(Pirate) \u0026\u0026 original.avatar.attached?\n    attachment = original.avatar\n    kopy.avatar.attach \\\n      :io           =\u003e StringIO.new(attachment.download),\n      :filename     =\u003e attachment.filename,\n      :content_type =\u003e attachment.content_type\n  end\nend\n\n# Rails 5.2, has_many_attached example 1 (attach one by one)\npirate.deep_clone include: :parrot do |original, kopy|\n  if kopy.is_a?(Pirate) \u0026\u0026 original.crew_members_images.attached?\n    original.crew_members_images.each do |attachment|\n      kopy.crew_members_images.attach \\\n        :io           =\u003e StringIO.new(attachment.download),\n        :filename     =\u003e attachment.filename,\n        :content_type =\u003e attachment.content_type\n    end\n  end\nend\n\n# Rails 5.2, has_many_attached example 2 (attach bulk)\npirate.deep_clone include: :parrot do |original, kopy|\n  if kopy.is_a?(Pirate) \u0026\u0026 original.crew_members_images.attached?\n    all_attachments_arr = original.crew_members_images.map do |attachment|\n      {\n        :io           =\u003e StringIO.new(attachment.download),\n        :filename     =\u003e attachment.filename,\n        :content_type =\u003e attachment.content_type\n      }\n    end\n    kopy.crew_members_images.attach(all_attachments_arr) # attach all at once\n  end\nend\n\n# Rails 6\npirate.deep_clone include: :parrot do |original, kopy|\n  if kopy.is_a?(Pirate) \u0026\u0026 original.avatar.attached?\n    original.avatar.open do |tempfile|\n      kopy.avatar.attach({\n        io: File.open(tempfile.path),\n        filename: original.avatar.blob.filename,\n        content_type: original.avatar.blob.content_type\n      })\n    end\n  end\nend\n```\n\n##### Shallow copy example\n\n```ruby\npirate.deep_clone include: :parrot do |original, kopy|\n  kopy.avatar.attach(original.avatar.blob) if kopy.is_a?(Pirate) \u0026\u0026 original.avatar.attached?\nend\n```\n\n### Skipping missing associations\n\nBy default, deep_cloneable will throw a `DeepCloneable::AssociationNotFoundException` error when an association cannot be found. You can also skip missing associations by specifying `skip_missing_associations` if needed, for example when you have associations on some (but not all) subclasses of an STI model:\n\n```ruby\npirate.deep_clone include: [:parrot, :rum], skip_missing_associations: true\n```\n\n### Note on Patches/Pull Requests\n\n- Fork the project.\n- Make your feature addition or bug fix.\n- Add tests for it. This is important so I don't break it in a\n  future version unintentionally.\n- Commit, do not mess with rakefile, version, or history.\n  (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)\n- Send me a pull request. Bonus points for topic branches.\n\n### Copyright\n\nCopyright \u0026copy; 2024 Reinier de Lange. See LICENSE for details.\n","funding_links":[],"categories":["Active Record","Ruby","模型"],"sub_categories":["Omniauth"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoiristo%2Fdeep_cloneable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmoiristo%2Fdeep_cloneable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoiristo%2Fdeep_cloneable/lists"}