views:

205

answers:

1

I want to build an XML map of all directories and files in my public/catalogs rails directory.(recursive map)

I would like it to be constructed with basic <directory> <file> element with name attribute equal to the dir or file name.

<catalogs>
 <file name="index.html">
 <directory name="foo">
    <file name="file1.html" />
    <directory name="bar">
       <file name="file2.html" />
    </directory>
 </directory>
</catalogs>

I am just not sure what the best way to do recursive map to xml - I looked for a plugin that might handle this since it seems like it something someone might have though to construct.

Any thoughts or direction on best way to create this?

+1  A: 

Well, I never found a plugin or any thing that seems to be built to do this... so I had to roll my own... here it is complete with attributes for sha and url since I needed them. Hope this helps someone else.

xml = Builder::XmlMarkup.new(:indent => 2,:escape_attrs => true)
xml.instruct!    
xml.catalogs(:version=>2) {list_entries("#{CATALOG_PATH}", xml)}
File.open("#{RAILS_ROOT}/public/catalogs.xml", 'w') {|f| f.write(xml.target!) }

def list_entries(dir,xml)
  Dir.glob("#{dir}/*") do |entry|
    if File::directory?(entry)
      xml.directory(:name=>File.basename(entry)) {
        list_entries(entry, xml)
      }
    else
      xml.file(:name=>File.basename(entry),:sha => Digest::SHA256.hexdigest(entry),
      :url=>entry.gsub("#{CATALOG_PATH}","#{CATALOG_URL}"))
    end
  end
end
Streamline