如何在Ruby下载之前获取远程文件的mtime?

Cih*_*ser 5 ruby http file download

我有下面的代码,它只是下载一个文件并保存.我想每隔30秒运行一次并检查远程文件的mtime是否已更改,如果有,则将其下载.为了这个目的,我将创建一个在无限循环的每次迭代后休眠30秒的线程,但是; 如何在不下载的情况下检查远程文件的mtime?

Net::HTTP.start($xmlServerHostname) { |http|
                resp = http.get($xmlServerPath+"levels.xml")
                open("levels.xml", "w") { |file|
                    file.write(resp.body)
                }
            }
Run Code Online (Sandbox Code Playgroud)

mik*_*kej 8

在你做http.get一个http.head之前,它只请求头文件而不下载正文(即文件内容),然后检查Last Modified标头的值是否已经改变.

例如

resp = http.head(($xmlServerPath+"levels.xml")
last_modified = resp['last-modified']
if last_modified != previous_last_modified
  # file has changed
end
Run Code Online (Sandbox Code Playgroud)

  • 我刚试过这个并且在同一个起始块中做两个似乎没问题. (2认同)