Method: Janeway::Enumerator#replace

Defined in:
lib/janeway/enumerator.rb

#replace(replacement = :no_replacement_value_was_given, &block) ⇒ void

This method returns an undefined value.

Assign the given value at every query match.

Parameters:

  • replacement (Object) (defaults to: :no_replacement_value_was_given)


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/janeway/enumerator.rb', line 59

def replace(replacement = :no_replacement_value_was_given, &block)
  if replacement != :no_replacement_value_was_given && block_given?
    raise Janeway::Error.new('#replace needs either replacement value or block, not both', @query)
  end

  # Avoid infinite loop when the replacement data would also be matched by the query
  previous = []
  each do |_, parent, key|
    # Update the previous match
    unless previous.empty?
      prev_parent, prev_key = *previous
      prev_parent[prev_key] = block_given? ? yield(prev_parent[prev_key]) : replacement
    end

    # Record this match to be updated later
    previous = [parent, key]
  end
  return if previous.empty?

  # Update the final match
  prev_parent, prev_key = *previous
  prev_parent[prev_key] = block_given? ? yield(prev_parent[prev_key]) : replacement
  nil
end