Class: Transmogrifier::Rules::Update

Inherits:
Object
  • Object
show all
Defined in:
lib/transmogrifier/rules/update.rb

Instance Method Summary collapse

Constructor Details

#initialize(selector, new_value) ⇒ Update

Returns a new instance of Update.



4
5
6
# File 'lib/transmogrifier/rules/update.rb', line 4

def initialize(selector, new_value)
  @selector, @new_value = selector, new_value
end

Instance Method Details

#apply!(input_hash) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/transmogrifier/rules/update.rb', line 8

def apply!(input_hash)
  top = Node.for(input_hash)
  *parent_keys, child_key = Selector.from_string(@selector).keys

  parents = top.find_all(parent_keys)
  raise SelectorNotFoundError, "#{parent_keys} does not select a node" unless parents.length > 0

  parents.each do |parent|
    if parent.class == HashNode
      raise SelectorNotFoundError, "no mapping for #{child_key} in parent node" unless parent.raw.has_key?(child_key)
      parent.append({child_key => @new_value})
    elsif parent.class == ArrayNode
      deleted_node = parent.delete(child_key)
      raise SelectorNotFoundError, "no node found with specified attributes" if deleted_node.nil?
      parent.append(@new_value)
    end
  end

  top.raw
end