Class: Alchemrest::HashPath

Inherits:
Object
  • Object
show all
Defined in:
lib/alchemrest/hash_path.rb

Overview

A utility for executing transformations against hashes scoped to specific parts of the hash defined by the ‘segments` of the path. The `Alchemrest::HashPath` class has one method `#walk` which will “walk” the path defined by the segments, yielding to a block provided by the calling code at each node it stops at. In that block, the calling code can transform the hash as it likes

Examples:

Using ‘Alchemrest::HashPath` to delete specific nodes from a hash

input = { user: { accounts: [{account_id: 1, transactions: [{transaction_id: 1, amount: 100}] }] } }
path = Alchemrest::HashPath.new([:user, :accounts, :transactions, :amount])
path.walk(input) do |_path, node, remaining_segments|
  if(remaining_segments.count == 1)
    node.delete(remaining_segments.last.key)
  end
end
input #=> { user: { accounts: [{account_id: 1, transactions: [{transaction_id: 1}] }] } }

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build_collection(definition) ⇒ Object

A helper method to quickly build a collection of hash paths from a rails style “StrongParams” hash arg.

Examples:

Create multiple hash paths from a strong params style hash

Alchemrest::HashPath.build_collection(user: { accounts: { transactions: [:id, :amount] } }) #=>
  [
    Alchemrest::HashPath(segments: [:accounts, :transactions, :id]),
    Alchemrest::HashPath(segments: [:accounts, :transactions, :amount])
  ]


28
29
30
31
32
33
34
# File 'lib/alchemrest/hash_path.rb', line 28

def self.build_collection(definition)
  paths = []
  visit_leaves(definition) do |value, path|
    paths << (path + [value])
  end
  paths.map { |path| new(path) }
end

Instance Method Details

#walk(input, &block) ⇒ Object

“Walks” the path defined by the segments of the HashPath, including individual items in nested collections. For each items it walks, it yields to the provided block, passing the current full path to that item, it’s value and the remaining segments of the path it has to walk. If it any point the input does not have a value for one of the segments, this method will stop traversing that portion of the hash. Note actions taken within the block are mutative, and will modify the original hash



41
42
43
# File 'lib/alchemrest/hash_path.rb', line 41

def walk(input, &block)
  traverse(input, segments, [], &block)
end