views:

80

answers:

1

Hi there, Is there an easy way to get the date modified of a file by using Net::SFTP?

It'd be nice to be able to do this:

Net::SFTP.start('some_server') do |sftp|
  sftp.dir.glob('*').each do |file|
    puts file.mtime
  end
end

But that's not possible (to my knowledge).

Berns.

+2  A: 

Your example code is almost there, you just need to use file.attributes.mtime where you had file.mtime.

Also, I'm guessing the code in the question was just an example, but in order for it to execute you also need to pass the username and password to start and pass the path as well as the pattern to glob. So a working example would be:

Net::SFTP.start('some_server', 'mike', :password => 'secret') do |sftp|
  sftp.dir.glob('.', '*').each do |file|
    puts file.attributes.mtime
  end
end

The value returned by mtime will be the number of seconds since the epoch so you may want to pass it to Time.at to convert it to a Time object.

In case you're curious, the other attributes available in the same way are:

  • permissions
  • uid
  • gid
  • size
  • atime (time of last access)
mikej
Beautiful! And excellent catch on the other example mishaps. Thanks Mike!
btelles