module MyData::XmlParser
Public Instance Methods
xml_to_resource(xml:, resource:, root: nil)
click to toggle source
# File lib/my_data/xml_parser.rb, line 6 def xml_to_resource(xml:, resource:, root: nil) h = transofrm_xml_to_hash(fix_xml(xml)) h = h[root] if root resource.new hash_mapping(h, resource) end
Private Instance Methods
fix_xml(xml)
click to toggle source
# File lib/my_data/xml_parser.rb, line 34 def fix_xml(xml) xml.strip.gsub("<", "<").gsub(">", ">") end
flatten(hash, resource)
click to toggle source
# File lib/my_data/xml_parser.rb, line 44 def flatten(hash, resource) return {} unless hash hash.each_with_object({}) do |(k, v), h| next if resource.attributes.none?(k) || !v mappings = resource.mappings[k] next h[k] = v unless mappings[:collection] && mappings[:collection_element_name] h[k] = v[mappings[:collection_element_name]] end end
hash_mapping(hash, resource)
click to toggle source
# File lib/my_data/xml_parser.rb, line 15 def hash_mapping(hash, resource) flatten(hash, resource).each_with_object({}) do |(key, value), h| mappings = resource.mappings[key] h[key] = value_mapping(value, mappings) end end
transofrm_xml_to_hash(xml)
click to toggle source
# File lib/my_data/xml_parser.rb, line 38 def transofrm_xml_to_hash(xml) Hash .from_xml(xml) .deep_transform_keys(&:underscore)["string"] end
value_mapping(value, mappings)
click to toggle source
# File lib/my_data/xml_parser.rb, line 23 def value_mapping(value, mappings) return value if mappings[:resource].nil? if mappings[:collection] value = value.is_a?(Array) ? value : [value] value.map { |v| hash_mapping(v, mappings[:resource]) } else hash_mapping(value, mappings[:resource]) end end