active_record_merger 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 82e89e6af09708612c603982a047916c65f9dd6922bcbec285d4b94f70d6b980
4
+ data.tar.gz: 1df6c7c113de356ad06943f281d1da1d6c45c36a91ff9e00aad345a0275dcc44
5
+ SHA512:
6
+ metadata.gz: 79207c42bef32d660bbf423e6d383884e9915e2da9303d790c7684702bd3a053b3cadf34beb51620ad6f2c7474c2fc19af7c03a223e55067d600554c02f1852c
7
+ data.tar.gz: 5f31936fb1c469aae52613b7d647f57ceb3fe06466da1549cd28e6ee251d2a35bb951f0c69f65363ba5efa4c2b77e442dfae21cda399541af7885b861ca90eb2
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="PropertiesComponent">{
4
+ &quot;keyToString&quot;: {
5
+ &quot;settings.editor.selected.configurable&quot;: &quot;settings.sync&quot;
6
+ }
7
+ }</component>
8
+ </project>
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at max@buslaev.net. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in active_record_merger.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Max Buslaev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,222 @@
1
+ # ActiveRecordMerger
2
+
3
+ The `ActiveRecordMerger` gem provides functionality for merging ActiveRecord objects along with their associated records. It's designed to simplify the process of combining duplicate records into a single record, while also ensuring that all associated data is correctly updated and maintained.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'active_record_merger'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```bash
16
+ bundle install
17
+ ```
18
+
19
+ Or install it yourself as:
20
+
21
+ ```bash
22
+ gem install active_record_merger
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ `ActiveRecordMerger` is designed to assist in merging two ActiveRecord objects and their associated records. This can be especially useful for consolidating duplicate records in your database.
28
+
29
+ ### Basic Setup
30
+
31
+ Before you begin, you must decide which of the two records will be the 'primary' record (the one to be kept) and which will be the 'secondary' record (the one to be merged and then optionally deleted). By default, without any custom logic, `ActiveRecordMerger` will not alter the attributes of the primary record.
32
+
33
+ ```ruby
34
+ primary_record = YourModel.find(primary_id)
35
+ secondary_record = YourModel.find(secondary_id)
36
+
37
+ merger = ActiveRecordMerger::RecordMerger.new(
38
+ primary_record,
39
+ secondary_record,
40
+ options: {} # Additional options can be provided here
41
+ )
42
+ merge_result = merger.call
43
+ ```
44
+
45
+ In this basic example, `merge_result` will contain information about the merge process, such as which associations were updated. Note that without additional configurations, no attributes from the secondary record will be copied to the primary record, and no records will be destroyed.
46
+
47
+
48
+ ## Default Options and Customization
49
+
50
+ The `ActiveRecordMerger` provides several options to customize the merging process. By default, these options are set to perform the most common actions expected during a record merge, but they can be customized to fit specific needs:
51
+
52
+ 1. **primary_record_resolver**: Determines which of the two records is considered the 'primary' record. By default, this is `nil`, meaning the first record provided to the merger is treated as the primary record.
53
+
54
+ 2. **merge_logic**: Defines how attributes from the secondary record should be merged into the primary record. The default is `nil`, indicating that no attribute merging occurs unless explicitly specified.
55
+
56
+ 3. **update_logic**: Provides custom logic for updating associations to re-associate the secondary record's related objects to the primary record. The default is `nil`, which updates foreign keys on direct associations (has_many, has_one) from the secondary to the primary record without additional logic.
57
+
58
+ 4. **destroy_merged_record**: Controls whether the secondary record should be destroyed after the merging process. The default is `false`, meaning the secondary record will remain in the database unless this option is explicitly set to `true`.
59
+
60
+ 5. **filter**: A callable object (like a lambda or Proc) that filters which associations should be updated based on certain criteria. By default, this is `->(assoc) { :belongs_to != assoc.type && assoc.through.nil? && !assoc.polymorphic }`, meaning we filter out all associations that are not direct or that are `:belongs_to`.
61
+
62
+ ### Using Filters
63
+
64
+ Filters allow you to specify which associations should be updated when merging records. This can be particularly useful if you only want to update certain types of associations or if you want to exclude specific associations based on certain conditions.
65
+
66
+ For example, if you only want to update `has_many` and `has_one` associations, and ignore `belongs_to` and `has_and_belongs_to_many` associations, you can use the following filter:
67
+
68
+ ```ruby
69
+ options = {
70
+ filter: ->(assoc) {
71
+ [:has_many, :has_one].include?(assoc.type) && !assoc.polymorphic
72
+ }
73
+ }
74
+ ```
75
+
76
+ In this example, the filter is a lambda that checks the type of each association. It returns `true` only for associations that are either `has_many` or `has_one` and not polymorphic, meaning only these associations will be considered for updating during the merge process.
77
+
78
+ You can customize this filter further to include your business logic, for example, excluding certain associations based on their name or custom options:
79
+
80
+ ```ruby
81
+ options = {
82
+ filter: ->(assoc) {
83
+ # Only update associations that are not polymorphic and are not named :account
84
+ !assoc.polymorphic && assoc.name != :account
85
+ }
86
+ }
87
+ ```
88
+
89
+ In this adjusted example, the filter additionally prevents any association named `:account` from being updated, regardless of its type.
90
+
91
+
92
+ ### Customizing Merge Behavior
93
+
94
+ You can customize the merge behavior by providing lambdas (or any other callable object) for various operations:
95
+
96
+ 1. **Primary Record Resolver (`:primary_record_resolver`):**
97
+
98
+ Determines which record should be considered primary. By default, the first record provided is treated as primary.
99
+
100
+ ```ruby
101
+ options = {
102
+ primary_record_resolver: lambda { |first, second| [first, second].min_by(&:created_at) }
103
+ }
104
+ ```
105
+
106
+ This example chooses the older record as the primary record.
107
+
108
+ 2. **Merge Logic (`:merge_logic`):**
109
+
110
+ Defines how to merge attributes from the secondary record into the primary record. By default, attributes are not merged.
111
+
112
+ ```ruby
113
+ options = {
114
+ merge_logic: lambda { |primary, secondary|
115
+ primary.update(name: secondary.name) if primary.name.blank?
116
+ }
117
+ }
118
+ ```
119
+
120
+ In this example, the primary record’s name is updated with the secondary's name if it was originally blank.
121
+
122
+ 3. **Update Logic (`:update_logic`):**
123
+
124
+ Custom logic for how associated records should be updated. This is important for re-associating related records from the secondary record to the primary record.
125
+
126
+ ```ruby
127
+ options = {
128
+ update_logic: lambda { |association, primary, secondary|
129
+ # Custom association update logic here
130
+ }
131
+ }
132
+ ```
133
+
134
+ Define how each association should handle transferring related records from the secondary to the primary record.
135
+
136
+ 4. **Destroy Merged Record (`:destroy_merged_record`):**
137
+
138
+ Determines whether the secondary record should be destroyed after merging.
139
+
140
+ ```ruby
141
+ options = {
142
+ destroy_merged_record: true
143
+ }
144
+ ```
145
+
146
+ If set to `true`, the secondary record will be deleted from the database after the merge process is complete.
147
+
148
+ ### Comprehensive Example
149
+
150
+ Combining all the options for a full-fledged merge process:
151
+
152
+ ```ruby
153
+ options = {
154
+ primary_record_resolver: lambda { |first, second| [first, second].min_by(&:created_at) },
155
+ merge_logic: lambda { |primary, secondary|
156
+ primary.update(name: secondary.name) if primary.name.blank?
157
+ },
158
+ update_logic: lambda { |association, primary, secondary|
159
+ # Update association references from secondary to primary
160
+ },
161
+ destroy_merged_record: true
162
+ }
163
+
164
+ merger = ActiveRecordMerger::RecordMerger.call(primary_record, secondary_record, options)
165
+ merge_result = merger.result
166
+ ```
167
+
168
+ This comprehensive example sets up a merger that chooses the oldest record as the primary, updates the primary record's name if it was blank, re-associates related records, and then deletes the secondary record after the merge.
169
+
170
+
171
+
172
+ ## Return Values and Error Handling
173
+
174
+ The `ActiveRecordMerger` utilizes `SimpleCommand` for executing the merge process, providing structured outcomes and error handling.
175
+
176
+ ### Result of Merge Operation
177
+
178
+ After the merge operation is completed using the `.call` method, the result can be accessed via the `@result` instance variable of the `RecordMerger` object. This result contains information about the merge process, typically including updated records count or other relevant data depending on the provided options and the merge logic:
179
+
180
+ ```ruby
181
+ merger = ActiveRecordMerger::RecordMerger.call(primary_record, secondary_record, options)
182
+
183
+ if merger.success?
184
+ puts "Merge successful!"
185
+ merge_details = merger.result
186
+ # Access detailed result information from merge_details
187
+ else
188
+ puts "Merge failed: #{merger.errors.full_messages.join(', ')}"
189
+ end
190
+ ```
191
+
192
+ In this example, `merger.result` will contain the outcome of the merge operation if it was successful. The exact structure of this result depends on how you've implemented your merge logic and what information you've chosen to include.
193
+
194
+ ### Handling Errors
195
+
196
+ If there are any issues during the merge process, such as validation failures or conflicts in the custom logic, the errors will be accumulated in the `.errors` method of the `RecordMerger` object. This method returns an instance of `SimpleCommand::Errors`, which provides a list of error messages:
197
+
198
+ ```ruby
199
+ unless merger.success?
200
+ puts "Merge failed due to the following errors:"
201
+ merger.errors.full_messages.each { |error_message| puts "- #{error_message}" }
202
+ end
203
+ ```
204
+
205
+ These errors can be used to understand what went wrong during the merge process and to inform users of the specific issues that need resolution. The `success?` method, provided by `SimpleCommand`, is a convenient way to check whether the operation completed successfully or if there were errors that prevented a successful merge.
206
+
207
+
208
+ ## Configuration
209
+
210
+ No additional configuration is required. However, you can customize the behavior by providing different options as shown above.
211
+
212
+ ## Contributing
213
+
214
+ Contributions are welcome! Feel free to open a pull request or an issue to propose changes or additions.
215
+
216
+ ## License
217
+
218
+ The gem is available as open source under the terms of the MIT License.
219
+
220
+ ## Code of Conduct
221
+
222
+ Everyone interacting in the ActiveRecordMerger project's codebase, issue trackers, chat rooms, and mailing lists is expected to follow the code of conduct.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/active_record_merger/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "active_record_merger"
7
+ spec.version = ActiveRecordMerger::VERSION
8
+ spec.authors = ["Max Buslaev"]
9
+ spec.email = ["max@buslaev.net"]
10
+
11
+ spec.summary = "A utility gem for merging ActiveRecord objects and their associated records with customizable logic."
12
+ spec.description = "ActiveRecordMerger provides an extendable framework for merging ActiveRecord models, including complex scenarios involving associations, while ensuring data integrity and providing hooks for custom merge logic."
13
+ spec.homepage = "https://github.com/austerlitz/active_record_merger"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/yourusername/active_record_merger"
19
+ spec.metadata["changelog_uri"] = "https://github.com/yourusername/active_record_merger/blob/main/CHANGELOG.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
26
+ end
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+
33
+ spec.add_dependency "activerecord", ">= 5.0"
34
+ spec.add_dependency "simple_command"
35
+
36
+ spec.add_development_dependency "rspec", "~> 3.10"
37
+ spec.add_development_dependency "pry", "~> 0.13.0"
38
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordMerger
4
+ module AssociationFinder
5
+ extend self
6
+
7
+ AssociationInfo = Struct.new(:name, :type, :class_name, :foreign_key, :through, :polymorphic,
8
+ :foreign_type, keyword_init: true)
9
+
10
+ # Finds and returns associations for a given ActiveRecord model.
11
+ def call(model_class, filter = ->(_assoc) { true })
12
+ model_class.reflect_on_all_associations.map do |assoc|
13
+ AssociationInfo.new(
14
+ name: assoc.name,
15
+ type: assoc.macro,
16
+ class_name: assoc.class_name,
17
+ foreign_key: assoc.foreign_key,
18
+ foreign_type: assoc.foreign_type,
19
+ through: assoc.options[:through],
20
+ polymorphic: assoc.options[:polymorphic],
21
+ )
22
+ end.select { |assoc| filter.call(assoc) }
23
+ end
24
+
25
+ end
26
+ end
27
+
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+ require 'simple_command'
3
+ require 'active_record'
4
+ require_relative 'association_finder'
5
+
6
+ module ActiveRecordMerger
7
+ ##
8
+ # This class performs the merging of two ActiveRecord objects of the same type.
9
+ # It updates associated records to reflect the merge and can optionally destroy the merged record.
10
+ #
11
+ class RecordMerger
12
+ prepend ::SimpleCommand
13
+
14
+ attr_reader :primary_record, :secondary_record, :update_counts, :options
15
+
16
+ ##
17
+ # Initializes the RecordMerger service object.
18
+ # @param first [ActiveRecord::Base] The record to merge into.
19
+ # @param second [ActiveRecord::Base] The record to merge from.
20
+ # @param options [Hash] The options to customize the merge process.
21
+ # @option options [Proc] :primary_record_resolver (nil) A lambda or Proc that determines which record is considered primary.
22
+ # @option options [Proc] :merge_logic (nil) A lambda or Proc that defines how to merge data from the secondary record into the primary record.
23
+ # @option options [Boolean] :destroy_merged_record (false) Whether to destroy the merged (secondary) record after the merge.
24
+ # @option options [Proc] :filter (->(assoc) { true }) A lambda or Proc that filters which associations should be updated.
25
+ # @option options [Proc] :update_logic (nil) A lambda or Proc that provides custom logic for updating associations.
26
+ #
27
+ def initialize(first, second, **options)
28
+ @_first = first
29
+ @_second = second
30
+ @options = default_options.merge(options)
31
+ @update_counts = {}
32
+ end
33
+
34
+ ##
35
+ # Executes the merge operation.
36
+ # Returns a hash containing the counts of updated records for each association, and the destruction status of the merged record.
37
+ # @return [Hash] The result of merge operation with update counts and destruction status.
38
+ #
39
+ def call
40
+ ::ActiveRecord::Base.transaction do
41
+ ensure_same_class
42
+ resolve_primary_and_secondary
43
+ apply_merge_logic
44
+ update_associations
45
+ destroy_secondary_record if options[:destroy_merged_record]
46
+ end
47
+ @update_counts
48
+ rescue => e
49
+ errors.add(:base, "Failed to merge records: #{e.message}")
50
+ nil
51
+ end
52
+
53
+ private
54
+
55
+ # Provides default options for merging records.
56
+ # @return [Hash] Default options for merge.
57
+ def default_options
58
+ {
59
+ filter: ->(assoc) {
60
+ :belongs_to != assoc.type && assoc.through.nil? && !assoc.polymorphic
61
+ },
62
+
63
+ destroy_merged_record: false,
64
+ primary_record_resolver: nil,
65
+ merge_logic: nil,
66
+ update_logic: nil,
67
+ }
68
+ end
69
+
70
+ def ensure_same_class
71
+ unless @_first.class == @_second.class
72
+ raise ::ArgumentError, 'Records must be of the same class to be merged.'
73
+ end
74
+ end
75
+
76
+ # Resolves which record should be considered the primary and which the secondary.
77
+ def resolve_primary_and_secondary
78
+ # Determine the primary record using the custom logic provided by the resolver.
79
+ @primary_record = options[:primary_record_resolver] ? options[:primary_record_resolver].call(@_first, @_second) : @_first
80
+
81
+ # The secondary record is the one that is not the primary.
82
+ @secondary_record = @_first == @primary_record ? @_second : @_first
83
+ end
84
+
85
+ # Applies custom logic for merging data from the secondary record into the primary record.
86
+ def apply_merge_logic
87
+ options[:merge_logic]&.call(@primary_record, @secondary_record)
88
+ end
89
+
90
+ # Updates associations from the secondary record to reference the primary record.
91
+ def update_associations
92
+ associations = AssociationFinder.call(@primary_record.class, options[:filter])
93
+ associations.each do |assoc|
94
+ if options[:update_logic]
95
+ # Here, we're passing the association, the primary record, and the secondary record to the custom logic
96
+ @update_counts[assoc.name] = options[:update_logic].call(assoc, @primary_record, @secondary_record)
97
+ else
98
+ # Default update logic: re-associate records from the secondary to the primary
99
+ associated_class = assoc.class_name.constantize
100
+ foreign_key = assoc.foreign_key
101
+ @update_counts[assoc.name] = associated_class.where(foreign_key => @secondary_record.id).update_all(foreign_key => @primary_record.id)
102
+ end
103
+ end
104
+ end
105
+
106
+ # Destroys the secondary record if flagged for destruction.
107
+ def destroy_secondary_record
108
+ @secondary_record.destroy
109
+ @update_counts[:destroyed] = @secondary_record.destroyed?
110
+ end
111
+
112
+ end
113
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordMerger
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "active_record_merger/version"
4
+ require_relative "active_record_merger/association_finder"
5
+ require_relative "active_record_merger/record_merger"
6
+
7
+ module ActiveRecordMerger
8
+ class Error < StandardError; end
9
+ # Your code goes here...
10
+ end
@@ -0,0 +1,4 @@
1
+ module ActiveRecordMerger
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,118 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_record_merger
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Max Buslaev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-03-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '5.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: simple_command
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.10'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.10'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 0.13.0
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 0.13.0
69
+ description: ActiveRecordMerger provides an extendable framework for merging ActiveRecord
70
+ models, including complex scenarios involving associations, while ensuring data
71
+ integrity and providing hooks for custom merge logic.
72
+ email:
73
+ - max@buslaev.net
74
+ executables: []
75
+ extensions: []
76
+ extra_rdoc_files: []
77
+ files:
78
+ - ".idea/workspace.xml"
79
+ - ".rspec"
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - active_record_merger.gemspec
86
+ - lib/active_record_merger.rb
87
+ - lib/active_record_merger/association_finder.rb
88
+ - lib/active_record_merger/record_merger.rb
89
+ - lib/active_record_merger/version.rb
90
+ - sig/active_record_merger.rbs
91
+ homepage: https://github.com/austerlitz/active_record_merger
92
+ licenses:
93
+ - MIT
94
+ metadata:
95
+ homepage_uri: https://github.com/austerlitz/active_record_merger
96
+ source_code_uri: https://github.com/yourusername/active_record_merger
97
+ changelog_uri: https://github.com/yourusername/active_record_merger/blob/main/CHANGELOG.md
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: 2.6.0
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubygems_version: 3.2.3
114
+ signing_key:
115
+ specification_version: 4
116
+ summary: A utility gem for merging ActiveRecord objects and their associated records
117
+ with customizable logic.
118
+ test_files: []