2014-10-21 59 views
0

我目前在命令行Dropbox應用程序中使用了futuresimple dropbox api gem。使用Ruby API從Dropbox下載

現在,我對我下載文件的方式有了第二個想法。代碼如下所示:

begin 
contents = env['dropbox-client'].download env['download_file_name'] 
rescue Dropbox::API::Error::NotFound => e 
    say "File Not Found! Could not download", :red 
    exit 1 
rescue Dropbox::API::Error => e 
    say "Connection to Dropbox failed (#{e})", :red 
    exit 1 
end 

File.open(env['download_file_name'], 'w') {|f| f.write(contents) } 

我覺得可以改進這段代碼。

我的基本問題是:

是否有從保管箱中contents API請求採取的身體,並用它來比我在這裏做的方式更好地創建一個文件更細緻入微的方式嗎?

回答

1

好,

File.open(env['download_file_name'], 'w') {|f| f.write(contents) } 

可以更清楚地寫着:

File.write(env['download_file_name'], contents) 

並嘗試這個未經測試的代碼:

rescue Dropbox::API::Error::NotFound, Dropbox::API::Error => e 
    msg = if (e == Dropbox::API::Error::NotFound) 
    "File Not Found! Could not download" 
    else 
    "Connection to Dropbox failed (#{e})" 
    end 

    say msg, :red 
    exit 1 
end 

(我在趕時間,但它看起來正確的)

+0

嗨!代碼更乾淨,但我更想到是否有更好的方式來獲取http正文並將其寫入文件。如果File.write是我使用它的最佳方式:) – 2014-10-23 18:14:05

+0

與「File.write」相比,您將很難找到寫入文件的更簡單和/或更好的方法。 – 2014-10-23 18:32:07