Module: Dry::Transformer::Recursion

Extended by:
Registry
Defined in:
lib/dry/transformer/recursion.rb

Overview

Recursive transformation functions

Examples:

require 'dry/transformer/recursion'

include Dry::Transformer::Helper

fn = t(:hash_recursion, t(:symbolize_keys))

fn["name" => "Jane", "address" => { "street" => "Street 1" }]
# => {:name=>"Jane", :address=>{:street=>"Street 1"}}

Constant Summary collapse

IF_ENUMERABLE =
-> fn { Conditional[:is, Enumerable, fn] }
IF_ARRAY =
-> fn { Conditional[:is, Array, fn] }
IF_HASH =
-> fn { Conditional[:is, Hash, fn] }

Class Method Summary collapse

Methods included from Registry

[], contain?, fetch, import, register, store

Class Method Details

.array_recursion(value, fn) ⇒ Array

Recursively apply the provided transformation function to an array

Examples:

Dry::Transformer(:array_recursion, -> s { s.compact })[
  [['Joe', 'Jane', nil], ['Smith', 'Doe', nil]]
]
# =>  [["Joe", "Jane"], ["Smith", "Doe"]]

Parameters:

  • (Array)

Returns:

  • (Array)


85
86
87
88
89
90
91
92
# File 'lib/dry/transformer/recursion.rb', line 85

def self.array_recursion(value, fn)
  result = fn[value]
  guarded = IF_ARRAY[-> v { array_recursion(v, fn) }]

  result.map! do |item|
    guarded[item]
  end
end

.hash_recursion(value, fn) ⇒ Hash

Recursively apply the provided transformation function to a hash

Examples:

Dry::Transformer(:hash_recursion, Dry::Transformer(:symbolize_keys))[
  ["name" => "Jane", "address" => { "street" => "Street 1", "zipcode" => "123" }]
]
# =>  {:name=>"Jane", :address=>{:street=>"Street 1", :zipcode=>"123"}}

Parameters:

  • (Hash)

Returns:

  • (Hash)


107
108
109
110
111
112
113
114
115
116
# File 'lib/dry/transformer/recursion.rb', line 107

def self.hash_recursion(value, fn)
  result = fn[value]
  guarded = IF_HASH[-> v { hash_recursion(v, fn) }]

  result.keys.each do |key|
    result[key] = guarded[result.delete(key)]
  end

  result
end

.recursion(value, fn) ⇒ Enumerable

Recursively apply the provided transformation function to an enumerable

Examples:

Dry::Transformer(:recursion, Dry::Transformer(:is, ::Hash, Dry::Transformer(:symbolize_keys)))[
  {
    'id' => 1,
    'name' => 'Jane',
    'tasks' => [
      { 'id' => 1, 'description' => 'Write some code' },
      { 'id' => 2, 'description' => 'Write some more code' }
    ]
  }
]
=> {
     :id=>1,
     :name=>"Jane",
     :tasks=>[
       {:id=>1, :description=>"Write some code"},
       {:id=>2, :description=>"Write some more code"}
     ]
   }

Parameters:

  • (Enumerable)

Returns:

  • (Enumerable)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/dry/transformer/recursion.rb', line 54

def self.recursion(value, fn)
  result = fn[value]
  guarded = IF_ENUMERABLE[-> v { recursion(v, fn) }]

  case result
  when ::Hash
    result.keys.each do |key|
      result[key] = guarded[result.delete(key)]
    end
  when ::Array
    result.map! do |item|
      guarded[item]
    end
  end

  result
end