简体   繁体   中英

How can I read directory or file information using Ruby/Rails or possibly PHP?

I need to reprocess some files using attachment_fu, but not all of the files.

I've seen a few posts asked about reading and listing files in a directory using Ruby, but does anyone know how to select the files based on the upload date or file parameters?

I can use either the date parameters for when the file was uploaded or look at the size of the jpg images (100 x 100) and if they were not properly resized, I will need to resize those.

Any ideas on how to access either of these pieces of information so that I can give them to a script that will reprocess the files using attachment_fu?

THANKS! Cindy

In PHP you can use SPL 's DirectoryIterator or FilesystemIterator . The Iterators extend from SplFileInfo which provides a comfortable API to the file attributes.

Example:

$it = new FilesystemIterator('/some/directory');
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
    echo $fileinfo->getCTime() . "\n";
    // etc ...
}

If you need to traverse deeper into the directory, you can do so with RecursiveDirectoryIterator . There is a number of questions about how to do this. Just search around SO.

The following script will recursively find all files named *.jpg in the current directory that are more than 3 days old and print the file name on the command line.

#!/usr/bin/env ruby

require 'rubygems'
require 'active_support'

AGE=3.days
PATTERN="*.jpg"

from_time = Time.now - AGE

jpgfiles = File.join("**", PATTERN)
Dir.glob(jpgfiles) do |file|
  puts file if File.mtime(file) < from_time
end

You could use this at the *nix command line as follows

some_command_that_takes_a_filelist $(path_to_ruby_script)

Be aware that using it in the above manner will blow up for huge file listings. If that is the case you may want to use xargs to pass the arguments to the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM