Module: Transproc::HashTransformations

Extended by:
Functions
Defined in:
lib/transproc/hash.rb

Overview

Transformation functions for Hash objects

Examples:

require 'transproc/hash'

include Transproc::Helper

fn = t(:symbolize_keys) >> t(:nest, :address, [:street, :zipcode])

fn["street" => "Street 1", "zipcode" => "123"]
# => {:address => {:street => "Street 1", :zipcode => "123"}}

Instance Method Summary collapse

Methods included from Functions

method_added

Instance Method Details

#accept_keys(hash, keys) ⇒ Hash

Accepts specified keys from a hash

Examples:

Transproc(:accept_keys, [:name])[name: 'Jane', email: '[email protected]']
# => {:name=>"Jane"}

Parameters:

  • hash (Hash)

    The input hash

  • keys (Array)

    The keys to be accepted

Returns:

  • (Hash)


185
186
187
# File 'lib/transproc/hash.rb', line 185

def accept_keys(hash, keys)
  accept_keys!(Hash[hash], keys)
end

#accept_keys!(hash, keys) ⇒ Object

Same as ‘:accept_keys` but mutates the hash

See Also:

  • HashTransformations.accept


194
195
196
# File 'lib/transproc/hash.rb', line 194

def accept_keys!(hash, keys)
  reject_keys!(hash, hash.keys - keys)
end

#fold(hash, key, tuple_key) ⇒ Hash

Folds array of tuples to array of values from a specified key

Examples:

source = {
  name: "Jane",
  tasks: [{ title: "be nice", priority: 1 }, { title: "sleep well" }]
}
Transproc(:fold, :tasks, :title)[source]
# => { name: "Jane", tasks: ["be nice", "sleep well"] }
Transproc(:fold, :tasks, :priority)[source]
# => { name: "Jane", tasks: [1, nil] }

Parameters:

  • hash (Hash)
  • key (Object)

    The key to fold values to

  • tuple_key (Object)

    The key to take folded values from

Returns:

  • (Hash)


306
307
308
# File 'lib/transproc/hash.rb', line 306

def fold(hash, key, tuple_key)
  fold!(Hash[hash], key, tuple_key)
end

#fold!(hash, key, tuple_key) ⇒ Object

Same as ‘:fold` but mutates the hash

See Also:



315
316
317
# File 'lib/transproc/hash.rb', line 315

def fold!(hash, key, tuple_key)
  hash.update(key => ArrayTransformations.extract_key(hash[key], tuple_key))
end

#map_keys(hash, fn) ⇒ Hash

Map all keys in a hash with the provided transformation function

Examples:

Transproc(:map_keys, -> s { s.upcase })['name' => 'Jane']
# => {"NAME" => "Jane"}

Parameters:

  • (Hash)

Returns:

  • (Hash)


31
32
33
# File 'lib/transproc/hash.rb', line 31

def map_keys(hash, fn)
  map_keys!(Hash[hash], fn)
end

#map_keys!(hash, fn) ⇒ Object

Same as ‘:map_keys` but mutates the hash

See Also:



40
41
42
43
# File 'lib/transproc/hash.rb', line 40

def map_keys!(hash, fn)
  hash.keys.each { |key| hash[fn[key]] = hash.delete(key) }
  hash
end

#map_value(hash, key, fn) ⇒ Hash

Map a key in a hash with the provided transformation function

Examples:

Transproc(:map_value, 'name', -> s { s.upcase })['name' => 'jane']
# => {"name" => "JANE"}

Parameters:

  • (Hash)

Returns:

  • (Hash)


209
210
211
# File 'lib/transproc/hash.rb', line 209

def map_value(hash, key, fn)
  hash.merge(key => fn[hash[key]])
end

#map_value!(hash, key, fn) ⇒ Object

Same as ‘:map_value` but mutates the hash

See Also:



218
219
220
# File 'lib/transproc/hash.rb', line 218

def map_value!(hash, key, fn)
  hash.update(key => fn[hash[key]])
end

#map_values(hash, fn) ⇒ Hash

Map all values in a hash using transformation function

Examples:

Transproc(:map_values, -> v { v.upcase })[:name => 'Jane']
# => {"name" => "JANE"}

Parameters:

  • (Hash)

Returns:

  • (Hash)


104
105
106
# File 'lib/transproc/hash.rb', line 104

def map_values(hash, fn)
  map_values!(Hash[hash], fn)
end

#map_values!(hash, fn) ⇒ Hash

Same as ‘:map_values` but mutates the hash

Parameters:

  • (Hash)

Returns:

  • (Hash)

See Also:



117
118
119
120
# File 'lib/transproc/hash.rb', line 117

def map_values!(hash, fn)
  hash.each { |key, value| hash[key] = fn[value] }
  hash
end

#nest(hash, key, keys) ⇒ Hash

Nest values from specified keys under a new key

Examples:

Transproc(:nest, :address, [:street, :zipcode])[street: 'Street', zipcode: '123']
# => {address: {street: "Street", zipcode: "123"}}

Parameters:

  • (Hash)

Returns:

  • (Hash)


233
234
235
# File 'lib/transproc/hash.rb', line 233

def nest(hash, key, keys)
  nest!(Hash[hash], key, keys)
end

#nest!(hash, root, keys) ⇒ Object

Same as ‘:nest` but mutates the hash

See Also:



242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/transproc/hash.rb', line 242

def nest!(hash, root, keys)
  nest_keys = hash.keys & keys

  if nest_keys.size > 0
    child = Hash[nest_keys.zip(nest_keys.map { |key| hash.delete(key) })]
    old_nest = hash[root]
    new_nest = old_nest.is_a?(Hash) ? old_nest.merge(child) : child
    hash.update(root => new_nest)
  else
    hash.update(root => {})
  end
end

#reject_keys(hash, keys) ⇒ Hash

Rejects specified keys from a hash

Examples:

Transproc(:reject_keys, [:name])[name: 'Jane', email: '[email protected]']
# => {:email => "[email protected]"}

Parameters:

  • hash (Hash)

    The input hash

  • keys (Array)

    The keys to be rejected

Returns:

  • (Hash)


160
161
162
# File 'lib/transproc/hash.rb', line 160

def reject_keys(hash, keys)
  reject_keys!(Hash[hash], keys)
end

#reject_keys!(hash, keys) ⇒ Object

Same as ‘:reject_keys` but mutates the hash

See Also:



169
170
171
# File 'lib/transproc/hash.rb', line 169

def reject_keys!(hash, keys)
  hash.reject { |k, _| keys.include?(k) }
end

#rename_keys(hash, mapping) ⇒ Hash

Rename all keys in a hash using provided mapping hash

Examples:

Transproc(:rename_keys, user_name: :name)[user_name: 'Jane']
# => {:name => "Jane"}

Parameters:

  • hash (Hash)

    The input hash

  • mapping (Hash)

    The key-rename mapping

Returns:

  • (Hash)


134
135
136
# File 'lib/transproc/hash.rb', line 134

def rename_keys(hash, mapping)
  rename_keys!(Hash[hash], mapping)
end

#rename_keys!(hash, mapping) ⇒ Object

Same as ‘:rename_keys` but mutates the hash

See Also:



143
144
145
146
# File 'lib/transproc/hash.rb', line 143

def rename_keys!(hash, mapping)
  mapping.each { |k, v| hash[v] = hash.delete(k) }
  hash
end

#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'                 }
  ]
}
Transproc(: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>)


347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/transproc/hash.rb', line 347

def 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

#stringify_keys(hash) ⇒ Hash

Stringify all keys in a hash

Examples:

Transproc(:stringify_keys)[:name => 'Jane']
# => {"name" => "Jane"}

Parameters:

  • (Hash)

Returns:

  • (Hash)


80
81
82
# File 'lib/transproc/hash.rb', line 80

def stringify_keys(hash)
  stringify_keys!(Hash[hash])
end

#stringify_keys!(hash) ⇒ Object

Same as ‘:stringify_keys` but mutates the hash

See Also:



89
90
91
# File 'lib/transproc/hash.rb', line 89

def stringify_keys!(hash)
  map_keys!(hash, Transproc(:to_string).fn)
end

#symbolize_keys(hash) ⇒ Hash

Symbolize all keys in a hash

Examples:

Transproc(:symbolize_keys)['name' => 'Jane']
# => {:name => "Jane"}

Parameters:

  • (Hash)

Returns:

  • (Hash)


56
57
58
# File 'lib/transproc/hash.rb', line 56

def symbolize_keys(hash)
  symbolize_keys!(Hash[hash])
end

#symbolize_keys!(hash) ⇒ Object

Same as ‘:symbolize_keys` but mutates the hash

See Also:



65
66
67
# File 'lib/transproc/hash.rb', line 65

def symbolize_keys!(hash)
  map_keys!(hash, Transproc(:to_symbol).fn)
end

#unwrap(hash, root, keys = nil) ⇒ Hash

Collapse a nested hash from a specified key

Examples:

Transproc(:unwrap, :address, [:street, :zipcode])[address: { street: 'Street', zipcode: '123' }]
# => {street: "Street", zipcode: "123"}

Parameters:

  • (Hash)

Returns:

  • (Hash)


266
267
268
269
# File 'lib/transproc/hash.rb', line 266

def unwrap(hash, root, keys = nil)
  copy = Hash[hash].merge(root => Hash[hash[root]])
  unwrap!(copy, root, keys)
end

#unwrap!(hash, root, selected = nil) ⇒ Object

Same as ‘:unwrap` but mutates the hash

See Also:



276
277
278
279
280
281
282
283
284
285
# File 'lib/transproc/hash.rb', line 276

def unwrap!(hash, root, selected = nil)
  if nested_hash = hash[root]
    keys = nested_hash.keys
    keys &= selected if selected
    hash.update(Hash[keys.zip(keys.map { |key| nested_hash.delete(key) })])
    hash.delete(root) if nested_hash.empty?
  end

  hash
end