Archive for December 2009

Listing files from a directory with Rails

Monday, December 7, 2009

Code to use in Ruby on Rails:

@files = Dir.glob("path-of-directory/*")
you can check whether any files are there or not ? by the below code,
@total_files = @files.size
Here, you will get all files and folders of the specified directory
If you want only files, then you can use below command,


@files = Dir.glob("path-of-directory/*.*")

Ok. now you can get files names by below code:

for file in @files
   puts file
end

If you want random file name and it's extension from @files, then

file_name = @files[rand(999)%@files.size]
ext = file_name[file_name.index('.')+1, file_name.length]


This is the best way I have found for pulling files from a directory and listing them in an array.

Powered by Blogger.