Directory Trees
Tuesday, March 06, 2007 by Nate Murray.
Below is a code snippet for putting directory tree into a data structure. Basically what I wanted was for each folder to be a hash with the key being the folder name and the value was an array of the files and folders it contains. For example: The folders:
content/policy
content/policy/privacy_policy.txt
content/policy/about_us.txt
content/policy/mean_policy
content/policy/mean_policy/nice_people.txt
content/policy/mean_policy/mean_people.txt
content/index.txt
content/content
content/content/misc
Creates the structure:
{"content"=>
[{"content"=>[{"misc"=>[]}]},
"index.txt",
{"policy"=>
["about_us.txt",
{"mean_policy"=>["mean_people.txt", "nice_people.txt"]},
"privacy_policy.txt"]}]}
The recursive code snippet is posted below:
def content_files_in_dir(dir, results = {}, opts = {})
return nil unless File.exist?(dir)
entries = Dir.entries(dir).delete_if { |f| f =~ /^\./ }
key = File.basename(dir)
values = []
entries.each do |entry|
full_entry = File.join(dir, entry)
values << ( File.directory?(full_entry) ?
content_files_in_dir(full_entry, results, opts) :
entry )
end
{ key => values }
end
Labels: recursion, ruby, snippets

» Post a Comment