« Testing for performance, part 1: Assess the problem space | Main | Please tell me when I'm being James Taggert »
Friday
Jan252008

Build a list of all files in a directory structure in Ruby

When testing web services it's often nice to be able to process a set of XML files. In other automation it can be nice to process batches of files as well. For some reason I can never find the following code when I need it and I always have to re-code it from scratch. That's always good practice, but it's annoying when I need it quickly.


def getFiles(directory)
returnFiles = []
Dir.glob(directory + '/*').each do | file |
if File.file?(file) then
returnFiles.push(file)
else
returnFiles.push(getFiles(file))
end
end
return returnFiles
end



So there it is. Google can now help me find my code whenever I need to build a list of all files in a directory structure.

Here is an example of how I might use that:


getFiles("C:/Regression Files").each do | testCaseFile |
resultsFile.puts(testCaseFile.to_s.split('/')[-1].chomp +
', methodName, ' + object.methodName(testCaseFile))
end


Reader Comments (2)

FYI, this can be a one-liner if you're looking for a specific file extension. The magic is in the '**'.

def getFiles(directory)
return Dir[directory + '/**/*.java']
end

September 29, 2008 | Unregistered Commenterselie

Cool. Thanks for the simplified version! Often I am...

September 29, 2008 | Unregistered CommenterMike Kelly

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>