Method: Dry::Transformer::HashTransformations.eval_values

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

.eval_values(hash, args, filters = []) ⇒ Object

Recursively evaluate hash values if they are procs/lambdas

rubocop:disable Metrics/PerceivedComplexity

Examples:

hash = {
  num: -> i { i + 1 },
  str: -> i { "num #{i}" }
}

t(:eval_values, 1)[hash]
# => {:num => 2, :str => "num 1" }

# with filters
t(:eval_values, 1, [:str])[hash]
# => {:num => #{still a proc}, :str => "num 1" }

Parameters:

  • (Hash)
  • args (Array, Object)

    Anything that should be passed to procs

  • filters (Array) (defaults to: [])

    A list of attribute names that should be evaluated



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/dry/transformer/hash_transformations.rb', line 396

def self.eval_values(hash, args, filters = [])
  hash.each_with_object({}) do |(key, value), output|
    output[key] =
      case value
      when Proc
        if filters.empty? || filters.include?(key)
          value.call(*args)
        else
          value
        end
      when ::Hash
        eval_values(value, args, filters)
      when ::Array
        value.map { |item|
          item.is_a?(Hash) ? eval_values(item, args, filters) : item
        }
      else
        value
      end
  end
end