Class: FreshBooks::BaseObject
- Inherits:
-
Struct
- Object
- Struct
- FreshBooks::BaseObject
- Defined in:
- lib/freshbooks.rb
Overview
BaseObject
Constant Summary collapse
- TYPE_MAPPINGS =
Maps field names (‘invoice_id’) to Ruby types (Fixnum)
{}
- MAPPING_FNS =
Anonymous methods for converting an XML element to its corresponding Ruby type
{ Fixnum => lambda { |xml_val| xml_val.text.to_i }, Float => lambda { |xml_val| xml_val.text.to_f }, BaseObject => lambda { |xml_val| BaseObject.class::new_from_xml }, Array => lambda do |xml_val| xml_val.elements.map do |elem| FreshBooks::const_get(elem.name.capitalize)::new_from_xml(elem) end end }
Instance Attribute Summary collapse
-
#resp ⇒ Object
Returns the value of attribute resp.
Class Method Summary collapse
-
.new_from_xml(xml_root) ⇒ Object
Create a new instance of this class from an XML element.
Instance Method Summary collapse
-
#to_xml ⇒ Object
Convert an instance of this class to an XML element.
Instance Attribute Details
#resp ⇒ Object
Returns the value of attribute resp.
136 137 138 |
# File 'lib/freshbooks.rb', line 136 def resp @resp end |
Class Method Details
.new_from_xml(xml_root) ⇒ Object
Create a new instance of this class from an XML element
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/freshbooks.rb', line 158 def self.new_from_xml(xml_root) object = self.new self.members.each do |field_name| node = xml_root.elements[field_name] next if node.nil? mapping = self::TYPE_MAPPINGS[field_name] if mapping object[field_name] = self::MAPPING_FNS[mapping].call(node) else object[field_name] = node.text.to_s end end return object end |
Instance Method Details
#to_xml ⇒ Object
Convert an instance of this class to an XML element
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
# File 'lib/freshbooks.rb', line 177 def to_xml # The root element is the class name, downcased elem_name = self.class.to_s.split('::').last.downcase root = Element.new elem_name # Add each BaseObject member to the root elem self.members.each do |field_name| value = self.send(field_name) if value.is_a?(Array) node = root.add_element(field_name) value.each { |array_elem| node.add_element(array_elem.to_xml) } elsif !value.nil? root.add_element(field_name).text = value end end root end |