Class: Lorax::ModifyDelta

Inherits:
Delta
  • Object
show all
Defined in:
lib/lorax/delta/modify_delta.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Delta

#inspect

Constructor Details

#initialize(node1, node2) ⇒ ModifyDelta

Returns a new instance of ModifyDelta.



5
6
7
8
# File 'lib/lorax/delta/modify_delta.rb', line 5

def initialize(node1, node2)
  @node1 = node1
  @node2 = node2
end

Instance Attribute Details

#node1Object

Returns the value of attribute node1.



3
4
5
# File 'lib/lorax/delta/modify_delta.rb', line 3

def node1
  @node1
end

#node2Object

Returns the value of attribute node2.



3
4
5
# File 'lib/lorax/delta/modify_delta.rb', line 3

def node2
  @node2
end

Instance Method Details

#apply!(doc) ⇒ Object

Raises:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/lorax/delta/modify_delta.rb', line 10

def apply!(doc)
  node = doc.at_xpath(node1.path)
  raise NodeNotFoundError, node1.path unless node

  if node.text? || node.type == Nokogiri::XML::Node::CDATA_SECTION_NODE
    node.content = node2.content
  else
    attributes = attributes_hash(node)
    attributes2 = attributes_hash(node2)
    if attributes != attributes2
      attributes .each { |name, value| node.remove_attribute(name) }
      attributes2.each { |name, value| node[name] = value }
    end
  end

  if node1.path != node2.path
    position = node2.parent.children.index(node2)
    target_parent = doc.at_xpath(node2.parent.path)
    raise NodeNotFoundError, node2.parent.path unless target_parent
    node.unlink
    insert_node(node, target_parent, position)
  end
end

#descriptorObject



34
35
36
37
38
39
40
41
42
# File 'lib/lorax/delta/modify_delta.rb', line 34

def descriptor
  if node1.text? || node1.type == Nokogiri::XML::Node::CDATA_SECTION_NODE
    [:modify, {:old => {:xpath => node1.path, :content => node1.to_s},
               :new => {:xpath => node2.path, :content => node2.to_s}}]
  else
    [:modify, {:old => {:xpath => node1.path, :name => node1.name, :attributes => node1.attributes.map{|k,v| [k, v.value]}},
               :new => {:xpath => node2.path, :name => node2.name, :attributes => node2.attributes.map{|k,v| [k, v.value]}}}]
  end
end