Method: Janeway::Enumerator#insert

Defined in:
lib/janeway/enumerator.rb

#insert(value) {|parent, array| ... } ⇒ Object

Insert ‘value` into the input at a location specified by a singular query.

This has restrictions:

* Only for singular queries
  (no wildcards, filter expressions, child segments, etc.)
* The "parent" node must exist
  eg. for $.a[1].name, the path $.a[1] must exist and be a Hash
* Cannot create array index N unless the array
  already has exactly N-1 elements
* If query path already exists, the block is called if provided.
  Otherwise an exception is raised.

Optionally, pass in a block to be called when there is already a value at the specified array index / hash key. The parent object and the array index or hash key will be yielded to the block.

Yield Parameters:

  • parent (Array, Hash)

    object

  • array (Intgeer, String)

    index or hash key



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/janeway/enumerator.rb', line 102

def insert(value, &block)
  # Query must point to a single target object
  unless @query.singular_query?
    msg = 'Janeway::Query#insert may only be used with a singular query'
    raise Janeway::Error.new(msg, @query)
  end

  # Find parent of new value
  parent, key, parent_path = find_parent

  # Insert new value into parent
  case parent
  when Hash then insert_into_hash(parent, key, value, parent_path, &block)
  when Array then insert_into_array(parent, key, value, parent_path, &block)
  else
    raise Error.new("cannot insert into basic type: #{parent.inspect}", @query.to_s)
  end
end