.

Coffee Powered

code and content

Stupid attachment_fu tricks, part 1

attachment_fu is fantastic, but it’s a bit limited for some purposes. Ever wanted to upload data from a URL instead of making people upload files? It’s a common problem!

Presume that we have a model named Image, which is our target for attachment_fu. Adding URL upload capability is surprisingly simple:

class Image < ActiveRecord::Base

	# Standard attachment_fu inclusion here
	has_attachment :storage => :file_system,
		:content_type => :image,
		:resize_to => "1024x1024>",
		:path_prefix => "public/images/cache/attached",
		:format => "jpg"

	# Allows the direct assignment of a URL to this image, which is the source image to save from
	def url=(v)
		self.uploaded_data = UrlUpload.new(v)
	end

	# Or, we can just pass a URL to Image#uploaded_data
	def uploaded_data=(filedata_or_url)
		if filedata_or_url.is_a? String and filedata_or_url.match /^http(s)?:\/\// then
			file = open(filedata_or_url)
			file.extend(UrlUpload)
			super(file)
		else
			super(filedata_or_url)
		end
	end
end

module UrlUpload
	def filename
		base_uri.to_s.split("/").last
	end

	def original_filename
		base_uri.to_s.split("/").last
	end
end

There you go. All you need now is Image.create(:url => "http://some.url/to/an/image.png") and when the model is saved, the image will be sucked down and saved. Easy!

  • http://almosteffortless.com Trevor Turk

    I'm not sure if it's better or anything, but I've been doing this like so:

    http://github.com/trevorturk/el-dorado/tree/maste…

    and

    http://github.com/trevorturk/el-dorado/tree/maste…

  • http://thejupitech.com/blog/add-remote-picture-with-attachment_fu/ Add remote picture with attachment_fu – Jupiter Technology

    [...] class Photo < ActiveRecord::Base require 'open-uri' belongs_to :user has_attachment :content_type => :image, :storage => (Rails.env === 'production' ? :s3 : :file_system), :max_size => 2.megabyte, :processor => :MiniMagick, :thumbnails => { :small => '100×100>', :medium => '150×150>', :large => '400×400>' }, :path_prefix => "public/images/#{table_name}" validates_as_attachment def source_uri=(uri) io = open(URI.parse(uri)) (class << io; self; end;).class_eval do define_method(:original_filename) { base_uri.path.split('/').last } end self.uploaded_data = io end end And we need to create a new photo using the facebppk open graph profile picture url: photo = Photo.new(:source_uri => "http://graph.facebook.com/#{current_user.facebook_uid}/picture") For an other similar solution can be found at Coffee Powerred Blog click here. [...]