Method: Dry::Transformer::HashTransformations.split

Defined in:
lib/dry/transformer/hash_transformations.rb

.split(hash, key, keys) ⇒ Array<Hash>

Splits hash to array by all values from a specified key

The operation adds missing keys extracted from the array to regularize the output.

Examples:

input = {
  name: 'Joe',
  tasks: [
    { title: 'sleep well', priority: 1 },
    { title: 'be nice',    priority: 2 },
    {                      priority: 2 },
    { title: 'be cool'                 }
  ]
}
Dry::Transformer(:split, :tasks, [:priority])[input]
=> [
    { name: 'Joe', priority: 1,   tasks: [{ title: 'sleep well' }]              },
    { name: 'Joe', priority: 2,   tasks: [{ title: 'be nice' }, { title: nil }] },
    { name: 'Joe', priority: nil, tasks: [{ title: 'be cool' }]                 }
  ]

Parameters:

  • hash (Hash)
  • key (Object)

    The key to split a hash by

  • subkeys (Array)

    The list of subkeys to be extracted from key

Returns:

  • (Array<Hash>)


362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/dry/transformer/hash_transformations.rb', line 362

def self.split(hash, key, keys)
  list = Array(hash[key])
  return [hash.reject { |k, _| k == key }] if list.empty?

  existing  = list.flat_map(&:keys).uniq
  grouped   = existing - keys
  ungrouped = existing & keys

  list = ArrayTransformations.group(list, key, grouped) if grouped.any?
  list = list.map { |item| item.merge(reject_keys(hash, [key])) }
  ArrayTransformations.add_keys(list, ungrouped)
end