Class: POSLavu::Row

Inherits:
Hash
  • Object
show all
Defined in:
lib/poslavu/row.rb

Overview

The POSLavu API principally operates on database rows exchanged in XML fragments. These are encapsulated as POSLavu::Row objects, which is really just a Hash with some additional methods.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash_to_copy = nil) ⇒ Row

Instantiate a Row, optionally copying an existing Hash.



8
9
10
11
12
13
14
# File 'lib/poslavu/row.rb', line 8

def initialize(hash_to_copy = nil)
  if hash_to_copy
    hash_to_copy.each { |key,value|
      self[key.to_sym] = value.to_s
    }
  end
end

Class Method Details

.from_nokogiri(xml) ⇒ Object

Instantiate a Row from a Nokogiri::XML::Node or similar. If you’re using the public interface, you shouldn’t ever need to call this.

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/poslavu/row.rb', line 25

def self.from_nokogiri(xml)   # :nodoc:
  raise ArgumentError, "argument is not a Nokogiri node" unless xml.kind_of?(Nokogiri::XML::Node)
  
  if xml.element? && xml.name == 'row'
    xml_row = xml
  else
    rows = xml.xpath('./row')
    raise ArgumentError, "argument does not directly contain a <row> element" if rows.empty?
    raise ArgumentError, "argument contains more than one <row> element" if rows.size > 1
    
    xml_row = rows.first
  end
  
  new.tap { |row|
    xml_row.element_children.each { |element|
      row[element.name.to_sym] = element.text
    }
  }
end

.from_xml(string) ⇒ Object

Instantiate a Row given a string containing a <row/> XML fragment. This XML fragment must contain exactly one <row> element at the root.



18
19
20
21
# File 'lib/poslavu/row.rb', line 18

def self.from_xml(string)
  fragment = Nokogiri::XML.fragment(string)
  from_nokogiri(fragment)
end

Instance Method Details

#to_nokogiri(doc) ⇒ Object

Adds this Row to a Nokogiri::XML::Node. If you’re using the public interface, you shouldn’t ever need to call this.



47
48
49
50
51
52
53
54
55
# File 'lib/poslavu/row.rb', line 47

def to_nokogiri(doc)  # :nodoc:
  row = doc.create_element('row'); doc.add_child(row)
  each { |key,value|
    element = doc.create_element(key.to_s)
    element.add_child(doc.create_text_node(value.to_s))
    row.add_child(element)
  }
  row
end

#to_xmlObject

Transform this Row into a string containing a <row/> XML fragment



58
59
60
61
62
# File 'lib/poslavu/row.rb', line 58

def to_xml
  doc = Nokogiri::XML::Document.new
  element = to_nokogiri(doc)
  element.to_s
end