How do I build a tree of directories?

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:

<folder name="directory name"

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.

On Jul 24, 3:06 pm, Ben K. [email protected] wrote:

</folder>

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).

  1. 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.