Skip to content

Instantly share code, notes, and snippets.

@bosskovic
Last active December 28, 2015 10:19
Show Gist options
  • Save bosskovic/7485480 to your computer and use it in GitHub Desktop.
Save bosskovic/7485480 to your computer and use it in GitHub Desktop.
An example of a rake task for re-uploading the aws files.
namespace :s3_files do
desc 'Reuploads the s3 files from the old locations'
task :reupload => :environment do
ok = 0
not_ok = 0
puts ' ', '-----', 'Re-uploading User avatars'
User.where('avatar IS NOT NULL').each do |user|
new_path = "uploads/user/#{user.uuid.to_s}/avatar"
old_path = "public/user/#{user.uuid.to_s}/avatar"
# url of the file with the old path
source_url = user.avatar.url.gsub(new_path, old_path)
source_file_reachable = file_reachable? source_url
if source_file_reachable
# url of the new file;
# nil unless the rake task is being successfully run again
target_url = user.avatar.url
# if the task is repeated, only unprocessed files should be processed
target_file_not_saved = !file_reachable?(target_url)
if target_file_not_saved
begin
user.cropping = true
user.remote_avatar_url = source_url
user.save!
ok += 1
rescue Exception => e
puts "Exception re-uploading file: #{source_url}", e.inspect
not_ok += 1
end
end
else
puts "Source file: #{source_url} not reachable"
not_ok += 1
end
end
puts "#{ok} files successfully re-uploaded" unless ok == 0
puts "#{not_ok} files not re-uploaded" unless not_ok == 0
end
def file_reachable?(url)
uri = URI(url)
request = Net::HTTP.new uri.host
response = request.request_head uri.path
response.code.to_i == 200
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment