Created
June 23, 2011 22:56
-
-
Save paveltyk/1043831 to your computer and use it in GitHub Desktop.
Ever needed to refresh (regenerate, update) attachment_fu attachments on amazon-s3? Here you go!
This file contains 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
def logger | |
@logger_for_attachment_fu_rake_task ||= Logger.new STDOUT | |
end | |
def raise_with_logger(msg) | |
logger.error msg | |
raise msg | |
end | |
def obtain_class | |
class_name = ENV['CLASS'] || ENV['class'] | |
raise_with_logger "Must specify CLASS" unless class_name | |
class_name | |
end | |
def obtain_id | |
ENV['ID'] || ENV['id'] | |
end | |
# attachment_fu uses some methods on updated_data. So implement them! | |
def extend_file_data_with_required_methods(image) | |
def image.original_filename | |
URI.unescape(base_uri.path).split('/').last.scan(/([\w\.-]*\.(?:png|jpe?g|gif|bmp))/i).flatten.first | |
end | |
def image.filename; original_filename; end | |
end | |
# Upload old original image, and then resave it. | |
# Attachment_fu should handle the rest (thumbnails, resizing, and etc.) | |
def refresh_attachments_for(instance) | |
logger.info "Refreshing #{instance.class.name} with id #{instance.id}..." | |
def instance.save_attachment?; true; end | |
image = open URI.parse(URI.escape instance.public_filename) | |
extend_file_data_with_required_methods(image) | |
logger.info "\tUploaded binary data for attachment. Size: #{"%.2fkb" % (image.size/1024.0)}." | |
logger.info "\tURL: #{instance.public_filename}" | |
logger.info "\tContent type: #{image.content_type}" | |
logger.info "\tFilename: #{image.original_filename}" | |
instance.uploaded_data = image | |
instance.save! | |
logger.info "\t#{instance.class.name} with id #{instance.id} refreshed successfully." | |
rescue => e | |
logger.error "!!! Failed to refresh: #{e}" | |
end | |
namespace :attachment_fu do | |
desc "Refresh attachments for given class. Use: rake attachment_fu:refresh CLASS=CustomAvatar and if you would like to refresh specific object, pass an ID attr." | |
task :refresh => :environment do | |
require 'open-uri' | |
klass = obtain_class.constantize | |
raise_with_logger "Wrong class specified (should repond to :content_types message)." unless klass.respond_to? :content_types | |
if obtain_id.present? | |
refresh_attachments_for klass.find(obtain_id) | |
else | |
klass.find_each :batch_size => 500, :conditions => {:parent_id => nil} do |instance| | |
refresh_attachments_for(instance) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice! Saved me a ton of time! Thanks!