[Awesome Ruby Gem] Use clowne gem to clone active_record objects including associations and several operations

Clowne

A flexible gem for cloning your models. Clowne focuses on ease of use and provides the ability to connect various ORM adapters.

Installation

You can install it as a gem:

1
$ gem install clowne

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# GitHub - clowne-rb/clowne: A flexible gem for cloning models
# https://github.com/clowne-rb/clowne
gem 'clowne', '1.3.0'

Usages

Assume that you have the following model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class User < ActiveRecord::Base
# create_table :users do |t|
# t.string :login
# t.string :email
# t.timestamps null: false
# end

has_one :profile
has_many :posts
end

class Profile < ActiveRecord::Base
# create_table :profiles do |t|
# t.string :name
# end
end

class Post < ActiveRecord::Base
# create_table :posts
end

Let’s declare our cloners first:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class UserCloner < Clowne::Cloner
adapter :active_record

include_association :profile, clone_with: SpecialProfileCloner
include_association :posts

nullify :login

# params here is an arbitrary Hash passed into cloner
finalize do |_source, record, **params|
record.email = params[:email]
end
end

class SpecialProfileCloner < Clowne::Cloner
adapter :active_record

nullify :name
end

Now you can use UserCloner to clone existing records:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
user = User.last
# => <#User id: 1, login: 'clown', email: 'clown@circus.example.com'>

operation = UserCloner.call(user, email: "[email protected]")
# => <#Clowne::Utils::Operation...>

operation.to_record
# => <#User id: nil, login: nil, email: 'fake@example.com'>

operation.persist!
# => true

cloned = operation.to_record
# => <#User id: 2, login: nil, email: 'fake@example.com'>

cloned.login
# => nil
cloned.email
# => "fake@example.com"

# associations:
cloned.posts.count == user.posts.count
# => true
cloned.profile.name
# => nil

Take a look at our documentation - https://clowne.evilmartians.io/#/ for more info!

References

[1] GitHub - clowne-rb/clowne: A flexible gem for cloning models - https://github.com/clowne-rb/clowne

[2] clowne | RubyGems.org | your community gem host - https://rubygems.org/gems/clowne/

[3] Clowne | Document - https://clowne.evilmartians.io/#/

[4] GitHub - moiristo/deep_cloneable: This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations. - https://github.com/moiristo/deep_cloneable

[5] GitHub - amoeba-rb/amoeba: A ruby gem to allow the copying of ActiveRecord objects and their associated children, configurable with a DSL on the model - https://github.com/amoeba-rb/amoeba