Created
October 7, 2009 11:05
-
-
Save blaines/203968 to your computer and use it in GitHub Desktop.
A recursive from_xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def import | |
xml = open(params[:_]).read # Param for opening an XML file ( http://localhost/import?_=http://localhost/companies.xml ) | |
doc = REXML::Document.new(xml) | |
@import = initialize_import(doc) | |
respond_to do |format| | |
format.html | |
end | |
end | |
# Process parent XML elements | |
def initialize_import(xml) | |
@array = Array.new | |
xml.elements.each do |e| | |
if e.size > 0 and e.attributes.get_attribute("type") and e.attributes.get_attribute("type").value.to_sym == :array | |
puts "Initialize #{e.name}" | |
e.elements.each do |ee| | |
puts " Initialized Import With #{ee.name.underscore.classify}" | |
model = ee.name.underscore.classify.constantize.new | |
ee.elements.each do |eee| | |
if eee.size > 0 and eee.attributes.get_attribute("type") and eee.attributes.get_attribute("type").value.to_sym == :array | |
puts " Process #{eee.name}" | |
process_import(eee,model) | |
elsif eee.size == 1 | |
puts " Set Attribute #{eee.name} = #{eee.text}" | |
model[eee.name]= eee.text | |
end | |
end | |
@array << model | |
end | |
else | |
puts "FAILED TO INITIALIZE IMPORT" | |
end | |
end | |
return @array | |
end | |
# Process children XML elements | |
def process_import(xml,model) | |
h = Hash.new | |
xml.elements.each do |e| | |
puts " Enumerating #{e.name.underscore.pluralize}" | |
i = model.send(e.name.underscore.pluralize).build | |
e.elements.each do |ee| | |
if ee.size > 0 and ee.attributes.get_attribute("type") and ee.attributes.get_attribute("type").value.to_sym == :array | |
puts " Encountered Array #{ee.name}" | |
process_import(ee,i) | |
elsif ee.size == 1 | |
puts " Set Attribute #{ee.name} = #{ee.text}" | |
i.send("#{ee.name.underscore}=", ee.text) | |
end | |
end | |
model | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment