Want to load a remote URL into an acts_as_attachment/attachment_fu model? Use this little utility class.
class UrlUpload
EXTENSIONS = {
"image/jpeg" => ["jpg", "jpeg", "jpe"],
"image/gif" => ["gif"],
"image/png" => ["png"]
}
attr_reader :original_filename, :attachment_data
def initialize(url)
@attachment_data = open(url)
@original_filename = determine_filename
end
def method_missing(symbol, *args)
if self.attachment_data.respond_to? symbol
self.attachment_data.send symbol, *args
else
super
end
end
private
def determine_filename
path = self.attachment_data.base_uri.path
filename = File.basename(path).downcase
filename = [filename.gsub(/\./, "_"), EXTENSIONS[self.content_type].first].join(".") unless EXTENSIONS[self.content_type].any? {|ext| filename.ends_with?("." + ext) }
filename
end
end
Now when you have the URL you want to load, do something like this:
@model.uploaded_data = UrlUpload.new(url)
Or better yet, make a pseudo-accessor on your aaa/attachment_fu model so you can stay "model-heavy".
def url=(value)
self.uploaded_data = UrlUpload.new(value)
end
No comments:
Post a Comment