Forum: Ruby How do I build a tree of directories?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B06f6479558ba7218963e93797d2f928?d=identicon&s=25 Ben Knight (biguniverse)
on 2007-07-25 00:06
Hello.  I need to send XML back to a client app listing all my
directories and sub-directories on the server.  The XML will look
something like this:

<folders>
    <folder name="directory-name">
         <folder name="directory name"
              <folder name="directory name">
              </folder>
         </folder>
    </folder>
</folders>

I'm doing this in Rails.  I have a couple of questions:

1. In my controller, how do I use something like Find.find(path) to do
this effectively? For example, do I need to make recursive calls to a
method for each subdirectory encountered?  Do I build an array of arrays
for the sub-directories?  A Hash?

2. Once my array of arrays or hash or whatever is built, what's the best
way to output this in my view?

Thanks in advance.
48e8a52db22ee2eeabb994dced226773?d=identicon&s=25 Skye Shaw!@#$ (Guest)
on 2007-07-26 00:45
(Received via mailing list)
On Jul 24, 3:06 pm, Ben Knight <anilsc...@yahoo.com> wrote:
>     </folder>
> </folders>
>
> I'm doing this in Rails.  I have a couple of questions:

> 1. In my controller, how do I use something like Find.find(path) to do
> this effectively? For example, do I need to make recursive calls to a
> method for each subdirectory encountered?

You'd want to use one of the Dir methods; foreach(), glob()...

Entry = Struct.new(:dir,:children)

def recurse(path)

 entry = Entry.new(path,[])

 #no "." or ".." dirs
 Dir["#{path}/*"].each do |e|
   if File.directory?(e)
      entry.children <<  recurse(e)
   end
 end

 entry

end

>  Do I build an array of arrays for the sub-directories?  A Hash?

Depends. If you just need the directory name and its children, then an
array of arrays will work. If you need additional information, then
use a Hash. Maybe a Struct (for fun).

> 2. Once my array of arrays or hash or whatever is built, what's the best
> way to output this in my view?

XML Builder, left as an exercise.

If you do not have additional requirements for the directory data,
i.e. you just want to output it as XML, then I'd say write the XML
with XML Builder as you recurse. Especially if your directory
structure is big.
This topic is locked and can not be replied to.