John Locke wrote:
> Hi,
> 
> I would like to make the following script in ruby:
> 
> Given a directory, for example /home, I would like to take ALL the
> subdirectories and files that are inside /home, and put them in a
> TreeView structure (from Ruby GTK), so I would have all those
> subdirectories and files arranged in that structure that I could then
> display as a graphic object.
> 
> I have found how to print all the stuff that is inside my current
> directory:
> 
> require 'find'
> Find.find('./') do |f| p f end
> 
> I could insert all what that command prints in the TreeView but then it
> would be all at the first level of the TreeView.
> 
> So I need to know, at each loop, what is at what level (which is the
> father, which is the son, etc), in order to insert it correctly in the
> TreeView.
> 
> In other words, right now I am able to do this:
> 
> /home/a
> /home/a1
> /home/a2
> /home/b
> 
> etc
> 
> And I would like to do this:
> 
> /home/a
>      /home/a1
>      /home/a2
> /home/b
> 
> Any ideas?
> 
> 
> Thanks.

Below code can be used to convert directory structure in xml.


require 'rubygems'
require 'rexml/document'

class DirectoryStructure
@@excludes = ["..","."]
@@doc = REXML::Document.new %{ <?xml version="1.0" encoding="UTF-8" ?> }

def self.traverse_directory(root_path)

  #traverse initial directory structure
  folder = @@doc.add_element( 'myroot',{'id' => root_path} )

  #call loop_path with root_path and parent_node
  loop_path(root_path,folder)
  #create xml file
   open( "final_directory_structure.xml", "w" ) do |f|
    f.puts @@doc
  end

end

def self.loop_path(path,parent_node)

dir_entries= Dir.entries(path)

# don't need '.','..'
dir_entries = dir_entries-['.','..']

dir_entries.each do | entry |

 # check if directory or file
 if File.directory?(path+"/"+entry)

   #Folders Loop -------------------------------------------------
   #Gets the directories of the current node.
   #It changes for each recursive call
   folder = parent_node.add_element( 'folder' ,{'label' =>entry
,'file_path' =>  path+"/"+entry } )
   loop_path( path+"/"+entry, folder )
 else
   #Files Loop ------------------------------------------------------
   file = parent_node.add_element( 'file' ,{'label' =>entry ,'file_path'
=>  path+"/"+entry } )

 end


end

end

#first call to traverse directory Please change the path---to your 
directory path
self.traverse_directory("Authentication/Authentication")

end
-- 
Posted via http://www.ruby-forum.com/.