Created
October 12, 2010 18:18
-
-
Save mindtonic/622641 to your computer and use it in GitHub Desktop.
Methods to build a Rake task to convert attachment_fu file store images to the Rackspace cloud
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# New Model with Cloudfiles Storage | |
class Photo < ActiveRecord::Base | |
has_attachment :content_type => :image, | |
:max_size => 1.megabyte, | |
:storage => :cloud_files, | |
:resize_to => "fill 128x128" | |
end | |
# Old Model with overwritten attachment methods | |
class OldPhoto < Photo | |
has_attachment :content_type => :image, | |
:max_size => 1.megabyte, | |
:storage => :file_system, | |
:resize_to => "fill 128x128" | |
end | |
# Method to check that a URL exists - confirms that a Cloudfile was uploaded successfully | |
require 'net/http' | |
def is_active_url(url) | |
begin | |
case Net::HTTP.get_response(URI.parse(url)) | |
when Net::HTTPSuccess then true | |
else false | |
end | |
rescue | |
false | |
end | |
end | |
# Convert method | |
require 'action_controller' | |
require 'action_controller/test_process.rb' | |
def convert(old, new) | |
if File.exists?(old.full_filename) | |
new.uploaded_data = ActionController::TestUploadedFile.new(old.full_filename, old.content_type) | |
new.save | |
puts "+++ Converted #{new.class.to_s} #{old.id}, it is located at #{new.public_filename}" | |
if is_active_url(new.public_filename) | |
File.delete(old.full_filename) | |
puts " - #{new.public_filename} Exists, Deleted #{old.full_filename}" | |
end | |
else | |
puts "--- No need to convert #{new.class.to_s} #{old.id}, it is located at #{new.public_filename}" | |
end | |
end | |
# Final composed Rake Task | |
namespace :convert do | |
desc 'Convert Filestore Image to Cloud File Storage' | |
task :photos => :environment do | |
class OldPhoto < Photo | |
has_attachment :content_type => :image, | |
:max_size => 1.megabyte, | |
:storage => :file_system, | |
:resize_to => "fill 128x128" | |
end | |
puts "Attempting to convert #{OldPhoto.all.count} Photos" | |
OldPhoto.all.each do |old| | |
new = Photo.find(old.id) | |
convert(old, new) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment