[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

How do I build a tree of directories?

Ben Knight

7/24/2007 10:07:00 PM

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.
--
Posted via http://www.ruby-....

1 Answer

skye.shaw

7/25/2007 5:22:00 AM

0

On Jul 24, 3:06 pm, Ben Knight <anilsc...@yahoo.com> wrote:
> 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?

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.