is-deep 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 411c8b523f176b63dfbbf1ead02fd233d797a2e2ef7e647c2ced7a2d990ddcea
4
+ data.tar.gz: d1b89698808ec204702acbc174e6f9c564b9e09a5688f98921a5200f1c939b99
5
+ SHA512:
6
+ metadata.gz: 205257ce4619b3762c9035af0477a37658a890d8d0eb2c501b00cd3235ec556c0f0ca75810208437bf545a1a00d67183938db8153b0a42be06ddc40a78827ccc
7
+ data.tar.gz: 8146ed7638cf40cb3f07902bc17d1b6bb21e8317c5c49857d4d68c9250e8c4bd3e3519ba26c25eb45c6a9a226b47828e7ebc1714d7a9308da752496afaaa45a8
data/LICENSE ADDED
@@ -0,0 +1,166 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
166
+
data/README.md ADDED
@@ -0,0 +1,181 @@
1
+ # is-deep
2
+
3
+ [![GitHub License](https://img.shields.io/github/license/inat-get/is-deep)](LICENSE)
4
+ [![Gem Version](https://badge.fury.io/rb/is-deep.svg?icon=si%3Arubygems)](https://badge.fury.io/rb/is-deep)
5
+ [![Ruby](https://github.com/inat-get/is-deep/actions/workflows/ruby.yml/badge.svg)](https://github.com/inat-get/is-deep/actions/workflows/ruby.yml)
6
+ ![Coverage](coverage-badge.svg)
7
+
8
+ Deep merge implementation for Ruby with configurable array strategies and circular reference protection.
9
+
10
+ ## Installation
11
+
12
+ Add to your Gemfile:
13
+
14
+ ```ruby
15
+ gem 'is-deep'
16
+ ```
17
+
18
+ Or install directly:
19
+
20
+ ```bash
21
+ gem install is-deep
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ### Basic Deep Merge
27
+
28
+ ```ruby
29
+ require 'is-deep'
30
+
31
+ # Hash merging
32
+ base = { a: 1, nested: { x: 1, y: 2 } }
33
+ other = { b: 2, nested: { y: 3, z: 4 } }
34
+
35
+ base.deep_merge(other)
36
+ # => { a: 1, b: 2, nested: { x: 1, y: 3, z: 4 } }
37
+
38
+ # Non-destructive (returns new hash)
39
+ result = base.deep_merge(other)
40
+ base # unchanged
41
+
42
+ # Destructive (modifies receiver)
43
+ base.deep_merge!(other)
44
+ ```
45
+
46
+ ### Array Merge Strategies
47
+
48
+ By default, arrays are concatenated:
49
+
50
+ ```ruby
51
+ { items: [1, 2] }.deep_merge({ items: [3, 4] })
52
+ # => { items: [1, 2, 3, 4] }
53
+ ```
54
+
55
+ Configure globally:
56
+
57
+ ```ruby
58
+ # Replace arrays entirely
59
+ IS::Deep.array_strategy = IS::Deep::ArrayStrategies::REPLACE
60
+ { items: [1] }.deep_merge({ items: [2] }) # => { items: [2] }
61
+
62
+ # Union (remove duplicates)
63
+ IS::Deep.array_strategy = IS::Deep::ArrayStrategies::UNION
64
+ { items: [1, 2] }.deep_merge({ items: [2, 3] }) # => { items: [1, 2, 3] }
65
+ ```
66
+
67
+ Or per-call:
68
+
69
+ ```ruby
70
+ { items: [1] }.deep_merge({ items: [2] }, array_strategy: IS::Deep::ArrayStrategies::REPLACE)
71
+ ```
72
+
73
+ ### Key-Based Array Merging
74
+
75
+ For arrays of hashes, merge by matching keys:
76
+
77
+ ```ruby
78
+ base = {
79
+ services: [
80
+ { name: 'web', port: 80, env: { DEBUG: '0' } },
81
+ { name: 'db', port: 5432 }
82
+ ]
83
+ }
84
+
85
+ other = {
86
+ services: [
87
+ { name: 'web', port: 8080, env: { DEBUG: '1', API_KEY: 'secret' } },
88
+ { name: 'cache', port: 6379 }
89
+ ]
90
+ }
91
+
92
+ strategy = IS::Deep::ArrayStrategies::KeyBased.new(:name)
93
+ base.deep_merge(other, array_strategy: strategy)
94
+
95
+ # Result:
96
+ # {
97
+ # services: [
98
+ # { name: 'web', port: 8080, env: { DEBUG: '1', API_KEY: 'secret' } },
99
+ # { name: 'db', port: 5432 },
100
+ # { name: 'cache', port: 6379 }
101
+ # ]
102
+ # }
103
+ ```
104
+
105
+ Auto-detect key from common candidates (`:id`, `:name`, `:key`, `:env`, `:host`):
106
+
107
+ ```ruby
108
+ strategy = IS::Deep::ArrayStrategies::KeyBased.new
109
+ # or use predefined
110
+ strategy = IS::Deep::ArrayStrategies::KEY_BASED[:id]
111
+ ```
112
+
113
+ ### Deep Duplication
114
+
115
+ Create independent copies with circular reference protection:
116
+
117
+ ```ruby
118
+ original = { a: { b: 1 } }
119
+ copy = original.deep_dup
120
+
121
+ copy[:a][:b] = 2
122
+ original[:a][:b] # => 1 (unchanged)
123
+
124
+ # Circular references are handled safely
125
+ circular = { name: 'root' }
126
+ circular[:self] = circular
127
+
128
+ copy = circular.deep_dup
129
+ copy[:self] # => points to copy itself, not original
130
+ ```
131
+
132
+ ### Thread Safety
133
+
134
+ Global strategy is thread-local by default:
135
+
136
+ ```ruby
137
+ IS::Deep.array_strategy = IS::Deep::ArrayStrategies::REPLACE
138
+
139
+ Thread.new do
140
+ # This thread has its own setting
141
+ IS::Deep.array_strategy = IS::Deep::ArrayStrategies::CONCAT
142
+ end.join
143
+
144
+ # Main thread still has REPLACE
145
+ ```
146
+
147
+ ### Custom Strategies
148
+
149
+ Implement any callable (lambda or class with `#call`):
150
+
151
+ ```ruby
152
+ # Lambda
153
+ IS::Deep.array_strategy = ->(base, other) { other.reverse + base }
154
+
155
+ # Class
156
+ class AppendUnique
157
+ def call(base, other)
158
+ (base + other).uniq
159
+ end
160
+ end
161
+
162
+ IS::Deep.array_strategy = AppendUnique.new
163
+ ```
164
+
165
+ ## API Reference
166
+
167
+ See [YARD documentation](https://rubydoc.info/gems/is-deep) for complete API.
168
+
169
+ Key classes:
170
+ - `IS::Deep` — configuration and core module
171
+ - `IS::Deep::ArrayStrategies` — built-in strategies
172
+ - `Hash#deep_merge`, `Hash#deep_merge!`, `Hash#deep_dup`
173
+ - `Array#deep_merge`, `Array#deep_merge!`, `Array#deep_dup`
174
+
175
+ ## Requirements
176
+
177
+ - Ruby >= 3.4
178
+
179
+ ## License
180
+
181
+ LGPL-3.0-only. See LICENSE file.
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" width="100" height="20">
2
+ <rect width="100" height="20" fill="#555"/>
3
+ <rect x="63" width="37" height="20" fill="green"/>
4
+ <text x="8" y="14" fill="#fff" font-family="Verdana" font-size="11">coverage</text>
5
+ <text x="66" y="14" fill="#fff" font-family="Verdana" font-size="11">94%</text>
6
+ </svg>
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IS; end
4
+
5
+ # Deep merge functionality for Ruby collections.
6
+ #
7
+ # This module provides deep merge, deep duplication, and configurable
8
+ # array merge strategies for Hash and Array classes.
9
+ #
10
+ # @example Basic usage
11
+ # { a: 1 }.deep_merge({ b: 2 }) # => { a: 1, b: 2 }
12
+ # { x: [1] }.deep_merge({ x: [2] }) # => { x: [1, 2] } (with concat strategy)
13
+ #
14
+ # @example Custom array strategy
15
+ # IS::Deep.array_strategy = IS::Deep::ArrayStrategies::REPLACE
16
+ # { x: [1] }.deep_merge({ x: [2] }) # => { x: [2] }
17
+ #
18
+ module IS::Deep
19
+
20
+ class << self
21
+
22
+ # @!attribute [rw] array_strategy
23
+ # The current array merge strategy.
24
+ #
25
+ # The strategy is thread-local. If not set for current thread,
26
+ # falls back to global default.
27
+ #
28
+ # @return [#call] Callable object accepting (base, other) arguments
29
+ # @see ArrayStrategies
30
+ def array_strategy
31
+ Thread.current[:is_deep_array_strategy] || @default_array_strategy
32
+ end
33
+
34
+ def array_strategy= strategy
35
+ @default_array_strategy ||= strategy
36
+ Thread.current[:is_deep_array_strategy] = strategy
37
+ end
38
+
39
+ end
40
+
41
+ # Стратегия по умолчанию — concat
42
+ self.array_strategy = lambda { |base, other| base + other }
43
+
44
+ # Performs deep merge on a duplicate of the receiver.
45
+ #
46
+ # Creates a deep copy of self, then merges other into it.
47
+ # Non-destructive operation — original receiver is not modified.
48
+ #
49
+ # @param other [Object] Object to merge into self
50
+ # @param array_strategy [#call, nil] Optional override for array merge strategy
51
+ # @return [IS::Deep] New object containing merged data
52
+ # @example
53
+ # base = { a: { b: 1 } }
54
+ # base.deep_merge({ a: { c: 2 } }) # => { a: { b: 1, c: 2 } }
55
+ # base # => { a: { b: 1 } } (unchanged)
56
+ def deep_merge other, array_strategy: nil
57
+ base = if self.respond_to?(:deep_dup)
58
+ self.deep_dup
59
+ elsif self.respond_to?(:dup)
60
+ self.dup
61
+ else
62
+ self
63
+ end
64
+ if base.respond_to?(:deep_merge!)
65
+ base.deep_merge! other, array_strategy: array_strategy
66
+ elsif base.respond_to?(:merge)
67
+ base.merge other
68
+ elsif base.respond_to?(:merge!)
69
+ base.merge! other
70
+ else
71
+ raise NoMethodError, "No merge methods in receiver (#{base.class})", caller_locations
72
+ end
73
+ end
74
+
75
+ private
76
+
77
+ def visited_data
78
+ Thread::current[:deep_merge_visited_data] ||= { data: {}, level: 0 }
79
+ end
80
+
81
+ def reset_visited_data!
82
+ Thread::current[:deep_merge_visited_data] = nil
83
+ end
84
+
85
+ protected
86
+
87
+ # @private
88
+ def visited_wrap
89
+ raise ArgumentError, "Block is required", caller_locations unless block_given?
90
+ data = visited_data
91
+ data[:level] += 1
92
+ yield data[:data]
93
+ ensure
94
+ data[:level] -= 1
95
+ if data[:level] == 0
96
+ reset_visited_data!
97
+ end
98
+ end
99
+
100
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IS
4
+ module Deep; end
5
+ end
6
+
7
+ # @api private
8
+ module IS::Deep::Info
9
+ NAME = 'is-deep'
10
+ VERSION = '0.8.0'
11
+ SUMMARY = 'Deep merge implementation'
12
+ AUTHOR = 'Ivan Shikhalev'
13
+ LICENSE = 'LGPL-3.0-only'
14
+ HOMEPAGE = 'https://github.com/inat-get/is-deep'
15
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'core'
4
+
5
+ # Namespace for array merge strategies.
6
+ #
7
+ # Strategies are callable objects (lambdas or class instances with #call)
8
+ # that determine how two arrays should be merged.
9
+ #
10
+ # @example Using built-in strategies
11
+ # IS::Deep.array_strategy = IS::Deep::ArrayStrategies::REPLACE
12
+ # IS::Deep.array_strategy = IS::Deep::ArrayStrategies::UNION
13
+ #
14
+ # @example Using KeyBased strategy
15
+ # strategy = IS::Deep::ArrayStrategies::KeyBased.new(:id)
16
+ # data.deep_merge(other, array_strategy: strategy)
17
+ #
18
+ module IS::Deep::ArrayStrategies
19
+
20
+ # Replace strategy: other array replaces base entirely.
21
+ #
22
+ REPLACE = lambda { |_, other| other }
23
+
24
+ # Concat strategy: append other to base (default).
25
+ #
26
+ # Preserves duplicates and order.
27
+ #
28
+ CONCAT = lambda { |base, other| base + other }
29
+
30
+ # Union strategy: combine arrays removing duplicates.
31
+ #
32
+ # Uses == for equality comparison. Order is preserved from base,
33
+ # then unique elements from other are appended.
34
+ #
35
+ UNION = lambda { |base, other| base | other }
36
+
37
+ # Key-based merge strategy for arrays of hashes.
38
+ #
39
+ # Matches elements by specified or auto-detected key, then deep merges
40
+ # matching elements. Unmatched elements are appended.
41
+ #
42
+ # @example Auto-detect key from common candidates (:id, :name, :key, :env, :host)
43
+ # strategy = IS::Deep::ArrayStrategies::KeyBased.new
44
+ # [{ id: 1, val: 1 }].deep_merge([{ id: 1, val: 2 }], array_strategy: strategy)
45
+ # # => [{ id: 1, val: 2 }]
46
+ #
47
+ # @example Explicit key
48
+ # strategy = IS::Deep::ArrayStrategies::KeyBased.new(:service_name)
49
+ #
50
+ class KeyBased
51
+
52
+ # @private
53
+ DEFAULT_KEY_CANDIDATES = [:id, :name, :key, :env, :host].freeze
54
+
55
+ # Initialize with optional explicit key.
56
+ #
57
+ # @param key [Symbol, String, nil] Key for matching elements.
58
+ # If nil, attempts auto-detection from first element.
59
+ def initialize key = nil
60
+ @key = key
61
+ end
62
+
63
+ # Execute merge strategy.
64
+ #
65
+ # @param base [Array] Original array
66
+ # @param other [Array] Array to merge into base
67
+ # @return [Array] Merged result
68
+ # @note Falls back to CONCAT behavior if key cannot be determined
69
+ def call base, other
70
+ effective_key = @key || detect_key(base)
71
+
72
+ unless effective_key
73
+ # Fallback к concat если не можем определить ключ
74
+ return base + other
75
+ end
76
+
77
+ indexed = index_by_key(base, effective_key)
78
+ merge_indexed base.dup, other, indexed, effective_key
79
+ end
80
+
81
+ private
82
+
83
+ def detect_key base
84
+ return nil if base.empty?
85
+ return nil unless base.first.is_a?(Hash)
86
+
87
+ DEFAULT_KEY_CANDIDATES.find { |k| base.first.key?(k) }
88
+ end
89
+
90
+ def index_by_key array, key
91
+ indexed = {}
92
+ array.each do |elem|
93
+ next unless elem.is_a?(Hash)
94
+ k = elem[key]
95
+ indexed[k] = elem unless k.nil?
96
+ end
97
+ indexed
98
+ end
99
+
100
+ def merge_indexed result, other, indexed, key
101
+ other.each do |elem|
102
+ unless elem.is_a?(Hash)
103
+ result << elem
104
+ next
105
+ end
106
+
107
+ k = elem[key]
108
+ if k && indexed.key?(k) && indexed[k].respond_to?(:deep_merge)
109
+ idx = result.index(indexed[k])
110
+ result[idx] = indexed[k].deep_merge(elem)
111
+ else
112
+ result << elem
113
+ end
114
+ end
115
+
116
+ result
117
+ end
118
+ end
119
+
120
+ # Predefined KeyBased instances for common keys.
121
+ KEY_BASED = {
122
+ detect: KeyBased::new(nil),
123
+ id: KeyBased::new(:id),
124
+ name: KeyBased::new(:name),
125
+ key: KeyBased::new(:key),
126
+ host: KeyBased::new(:host),
127
+ }
128
+
129
+ end
data/lib/is-deep.rb ADDED
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'is-deep/core'
4
+ require_relative 'is-deep/strategies'
5
+
6
+ class Hash
7
+ include IS::Deep
8
+
9
+ # Creates deep copy of hash with all nested structures.
10
+ #
11
+ # Handles circular references correctly. Preserves default values
12
+ # and default_proc if present.
13
+ #
14
+ # @return [Hash] Deep copy of self
15
+ # @example
16
+ # h = { a: { b: 1 } }
17
+ # copy = h.deep_dup
18
+ # copy[:a][:b] = 2
19
+ # h[:a][:b] # => 1 (unchanged)
20
+ def deep_dup
21
+ visited_wrap do |visited|
22
+ self_id = self.object_id
23
+ return visited[self_id] if visited.has_key?(self_id)
24
+ result = {}
25
+ visited[self_id] = result
26
+ if self.default_proc != nil
27
+ result.default_proc = self.default_proc
28
+ elsif self.default != nil
29
+ result.default = self.default
30
+ end
31
+ self.each do |key, value|
32
+ id = value.object_id
33
+ result[key] = if visited.has_key?(id)
34
+ visited[id]
35
+ elsif value.respond_to?(:deep_dup)
36
+ visited[id] = value.deep_dup
37
+ elsif value.respond_to?(:dup)
38
+ visited[id] = value.dup
39
+ else
40
+ visited[id] = value
41
+ end
42
+ end
43
+ result
44
+ end
45
+ end
46
+
47
+ # Deep merges other hash into self, modifying receiver.
48
+ #
49
+ # Recursively merges nested hashes. For conflicting values where
50
+ # old value responds to #can_merge? and returns true, attempts
51
+ # recursive merge. Otherwise replaces with new value.
52
+ #
53
+ # @param other [Hash, #to_hash] Hash or hash-like object to merge
54
+ # @param array_strategy [#call, nil] Override array merge strategy
55
+ # @return [self] Modified receiver
56
+ # @example
57
+ # h = { a: { b: 1 } }
58
+ # h.deep_merge!({ a: { c: 2 } })
59
+ # h # => { a: { b: 1, c: 2 } }
60
+ def deep_merge! other, array_strategy: nil
61
+ visited_wrap do |visited|
62
+ id = self.object_id
63
+ return self if visited.has_key?(id)
64
+ visited[id] = self
65
+ source = if other.is_a?(Hash)
66
+ other
67
+ elsif other.respond_to?(:to_hash)
68
+ other.to_hash
69
+ else
70
+ raise ArgumentError, "Unsupported type of source: (#{ other.class })", caller_locations
71
+ end
72
+ source.each do |key, value|
73
+ if self.has_key?(key)
74
+ old = self[key]
75
+ if old.respond_to?(:can_merge?) && old.can_merge?(value)
76
+ old.deep_merge! value, array_strategy: array_strategy
77
+ else
78
+ self[key] = value
79
+ end
80
+ else
81
+ self[key] = value
82
+ end
83
+ end
84
+ self
85
+ end
86
+ end
87
+
88
+ # Checks if other can be merged with this hash.
89
+ #
90
+ # @param other [Object] Object to check
91
+ # @return [Boolean] True if other is hash-like
92
+ def can_merge?(other)
93
+ other.is_a?(Hash) || other.respond_to?(:to_hash)
94
+ end
95
+
96
+ end
97
+
98
+ class Array
99
+ include IS::Deep
100
+
101
+ # Creates deep copy of array with all nested structures.
102
+ #
103
+ # Handles circular references correctly.
104
+ #
105
+ # @return [Array] Deep copy of self
106
+ def deep_dup
107
+ visited_wrap do |visited|
108
+ self_id = self.object_id
109
+ return visited[self_id] if visited.has_key?(self_id)
110
+ result = []
111
+ visited[self_id] = result
112
+ self.each do |item|
113
+ id = item.object_id
114
+ value = if visited.has_key?(id)
115
+ visited[id]
116
+ elsif item.respond_to?(:deep_dup)
117
+ visited[id] = item.deep_dup
118
+ elsif item.respond_to?(:dup)
119
+ visited[id] = item.dup
120
+ else
121
+ visited[id] = item
122
+ end
123
+ result << value
124
+ end
125
+ result
126
+ end
127
+ end
128
+
129
+ # Deep merges other array into self, modifying receiver.
130
+ #
131
+ # Uses configured or provided array_strategy to determine
132
+ # merge semantics. Strategy receives (base, other) and returns
133
+ # result array.
134
+ #
135
+ # @param other [Array, #to_ary] Array or array-like object to merge
136
+ # @param array_strategy [#call, nil] Override array merge strategy
137
+ # @return [self] Modified receiver
138
+ def deep_merge! other, array_strategy: nil
139
+ visited_wrap do |visited|
140
+ id = self.object_id
141
+ return self if visited.has_key?(id)
142
+ visited[id] = self
143
+ source = if other.is_a?(Array)
144
+ other
145
+ elsif other.respond_to?(:to_ary)
146
+ other.to_ary
147
+ else
148
+ raise ArgumentError, "Unsupported type of source: (#{other.class})", caller_locations
149
+ end
150
+
151
+ strategy = array_strategy || IS::Deep.array_strategy
152
+ result = strategy.call(self, source)
153
+
154
+ self.clear
155
+ result.each { |item| self << item }
156
+
157
+ self
158
+ end
159
+ end
160
+
161
+ # Checks if other can be merged with this array.
162
+ #
163
+ # @param other [Object] Object to check
164
+ # @return [Boolean] True if other is array-like
165
+ def can_merge? other
166
+ other.is_a?(Array) || other.respond_to?(:to_ary)
167
+ end
168
+
169
+ end
170
+
metadata ADDED
@@ -0,0 +1,128 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: is-deep
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.8.0
5
+ platform: ruby
6
+ authors:
7
+ - Ivan Shikhalev
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rake
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rspec
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: simplecov
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: yard
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ - !ruby/object:Gem::Dependency
69
+ name: redcarpet
70
+ requirement: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ type: :development
76
+ prerelease: false
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ - !ruby/object:Gem::Dependency
83
+ name: rdoc
84
+ requirement: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ type: :development
90
+ prerelease: false
91
+ version_requirements: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ executables: []
97
+ extensions: []
98
+ extra_rdoc_files: []
99
+ files:
100
+ - LICENSE
101
+ - README.md
102
+ - coverage-badge.svg
103
+ - lib/is-deep.rb
104
+ - lib/is-deep/core.rb
105
+ - lib/is-deep/info.rb
106
+ - lib/is-deep/strategies.rb
107
+ homepage: https://github.com/inat-get/is-deep
108
+ licenses:
109
+ - LGPL-3.0-only
110
+ metadata: {}
111
+ rdoc_options: []
112
+ require_paths:
113
+ - lib
114
+ required_ruby_version: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - ">="
117
+ - !ruby/object:Gem::Version
118
+ version: '3.4'
119
+ required_rubygems_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ requirements: []
125
+ rubygems_version: 3.6.9
126
+ specification_version: 4
127
+ summary: Deep merge implementation
128
+ test_files: []