Module: XmlResource::Model::ClassMethods

Defined in:
lib/xml_resource/model.rb

Instance Method Summary collapse

Instance Method Details

#basenameObject



49
50
51
# File 'lib/xml_resource/model.rb', line 49

def basename
  name.sub(/^.*::/, '')
end

#collection_from_xml(xml_or_string, default_attrs = {}) ⇒ Object



45
46
47
# File 'lib/xml_resource/model.rb', line 45

def collection_from_xml(xml_or_string, default_attrs = {})
  parse(xml_or_string).search(root).map { |element| from_xml(element, default_attrs) }.compact
end

#from_xml(xml_or_string, default_attrs = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/xml_resource/model.rb', line 18

def from_xml(xml_or_string, default_attrs = {})
  xml_or_string and xml = parse(xml_or_string) or return
  attrs = {}
  self.attributes.each do |name, options|
    if xpath = attribute_xpath(name)
      node = xml.at(xpath)
      value = node ? node.inner_text : nil
      if !value.nil? && type = attribute_type(name)
        value = cast_to(type, value)
      end
      attrs[name] = value
    end
  end
  instance = new(attrs.reject { |k, v| v.nil? }.reverse_merge(default_attrs))
  self.objects.each do |name, options|
    if xpath = object_xpath(name)
      instance.public_send("#{name}=", object_class(name).from_xml(xml.at(xpath)))
    end
  end
  self.collections.each do |name, options|
    if xpath = collection_xpath(name)
      instance.public_send("#{name}=", collection_class(name).collection_from_xml(xml.at(xpath)))
    end
  end
  instance
end

#rootObject



53
54
55
# File 'lib/xml_resource/model.rb', line 53

def root
  self.root_path || "./#{inflect(basename)}"
end

#root=(root) ⇒ Object



57
58
59
# File 'lib/xml_resource/model.rb', line 57

def root=(root)
  self.root_path = root
end