Class: IS::Deep::ArrayStrategies::KeyBased

Inherits:
Object
  • Object
show all
Defined in:
lib/is-deep/strategies.rb

Overview

Key-based merge strategy for arrays of hashes.

Matches elements by specified or auto-detected key, then deep merges matching elements. Unmatched elements are appended.

Examples:

Auto-detect key from common candidates (:id, :name, :key, :env, :host)

strategy = IS::Deep::ArrayStrategies::KeyBased.new
[{ id: 1, val: 1 }].deep_merge([{ id: 1, val: 2 }], array_strategy: strategy)
# => [{ id: 1, val: 2 }]

Explicit key

strategy = IS::Deep::ArrayStrategies::KeyBased.new(:service_name)

Constant Summary collapse

DEFAULT_KEY_CANDIDATES =
[:id, :name, :key, :env, :host].freeze

Instance Method Summary collapse

Constructor Details

#initialize(key = nil) ⇒ KeyBased

Initialize with optional explicit key.

Parameters:

  • key (Symbol, String, nil) (defaults to: nil)

    Key for matching elements. If nil, attempts auto-detection from first element.



59
60
61
# File 'lib/is-deep/strategies.rb', line 59

def initialize key = nil
  @key = key
end

Instance Method Details

#call(base, other) ⇒ Array

Note:

Falls back to CONCAT behavior if key cannot be determined

Execute merge strategy.

Parameters:

  • base (Array)

    Original array

  • other (Array)

    Array to merge into base

Returns:

  • (Array)

    Merged result



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/is-deep/strategies.rb', line 69

def call base, other
  effective_key = @key || detect_key(base)

  unless effective_key
    # Fallback к concat если не можем определить ключ
    return base + other
  end

  indexed = index_by_key(base, effective_key)
  merge_indexed base.dup, other, indexed, effective_key
end