Add remote picture with attachment_fu

Yes I know, we should say good bye attachment_fu and hello papaerclip. But I don’t have much choice in my case, the project is to integrate facebook open graph into an existing web application. So my focus was to add on the facebook features not to review and enhance the current code. So how to save the facebook profile pictures as user’s avatar. In other word I need to get the photo from remote url using attachment_fu.

If you user paperclip, this can be done using paperclip url support. For attachment_fu you will need to add some code to your photo class.

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 => '100x100>',
   :medium => '150x150>',
   :large => '400x400>' },
 :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.

Posted in Rails, Ruby, Technologies.

Tagged with , , , .


2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. sid_ says

    This great code . Could you explain this a bit to me. Do you end up storing the io object in the uploaded_data field.

  2. tyson says

    Yes, and the final data will be store depend on how you define of storage mechanism, in my case it will be file_system for development and s3 for production



Some HTML is OK

or, reply to this post via trackback.