How do I build a tree of directories?

B

Ben Knight

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

Skye Shaw!@#$

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top