Module: ROXML::ClassMethods::Operations

Defined in:
lib/roxml.rb

Instance Method Summary collapse

Instance Method Details

#from_xml(data, *initialization_args) ⇒ Object

Creates a new Ruby object from XML using mapping information annotated in the class.

The input data is either an XML::Node, String, Pathname, or File representing the XML document.

Example

book = Book.from_xml(File.read("book.xml"))

or

book = Book.from_xml("<book><name>Beyond Java</name></book>")

initialization_args passed into from_xml will be passed into the object’s .new, prior to populating the xml_attrs.

After the instatiation and xml population

See also: xml_initialize



550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/roxml.rb', line 550

def from_xml(data, *initialization_args)
  xml = XML::Node.from(data)

  new(*initialization_args).tap do |inst|
    inst.roxml_references = roxml_attrs.map {|attr| attr.to_ref(inst) }

    inst.roxml_references.each do |ref|
      value = ref.value_in(xml)
      inst.respond_to?(ref.opts.setter) \
        ? inst.send(ref.opts.setter, value) \
        : inst.instance_variable_set(ref.opts.instance_variable_name, value)
    end
    inst.send(:after_parse) if inst.respond_to?(:after_parse, true)
  end
rescue ArgumentError => e
  raise e, e.message + " for class #{self}"
end