Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a remote-file's mtime before downloading it in Ruby?

I have the below code, which simply downloads a file and saves it. I want to run it every 30 seconds and check if the remote-file's mtime has changed and download it if it has. I'll be creating a thread which sleeps 30seconds after every iteration of an endless loop for that purpose, but; how do I check a remote file's mtime without downloading it?

Net::HTTP.start($xmlServerHostname) { |http|
                resp = http.get($xmlServerPath+"levels.xml")
                open("levels.xml", "w") { |file|
                    file.write(resp.body)
                }
            }
like image 440
Cihan Keser Avatar asked Oct 02 '09 11:10

Cihan Keser


2 Answers

Before you do your http.get do an http.head which requests just the headers without downloading the body (i.e. the file contents) then check if the value of the Last Modified header has changed.

e.g.

resp = http.head(($xmlServerPath+"levels.xml")
last_modified = resp['last-modified']
if last_modified != previous_last_modified
  # file has changed
end
like image 169
mikej Avatar answered Oct 31 '22 17:10

mikej


You can try to send the If-Modified-Since header with a correctly formatted date.

If the server supports it, it can answer just with a 304 Not Modified status (without any content) or the full content if the file has been modified.

like image 29
Vincent Robert Avatar answered Oct 31 '22 18:10

Vincent Robert