Thursday 24 November 2011

Paperclip: Image or Photos from url

In general, Paperclip accepts file uploaded from local machine. However we can extend it to support image from url (Ex., Saving user avatars from twitter or facebook)

app/models/user.rb

  has_attached_file :avatar, ....
  attr_accessor :avatar_url
  def avatar_url=(img_url)
    io = open(URI.parse(img_url))
    # define original_filename meth on io, dynamically
    def io.original_filename; base_uri.path.split('/').last; end
    self.avatar = (io.original_filename.blank? ? nil : io)
  rescue Exception => ex
    puts ex.message
    Rails.logger.info "Error while parsing avatar: #{ex.message}"
  ensure
    io.close
    @avatar_url = img_url
  end

Glitch : OpenURI.open, returns an StringIO object, which might not be as efficient as a Tempfile. So considering adding this patch.


config/initializers/open_uri_patch.rb

require 'open-uri'

# make OpenURI to use tempfiles instead of io.
# Patched from http://snippets.dzone.com/posts/show/3994
OpenURI::Buffer.module_eval do
  remove_const :StringMax
  const_set :StringMax, 0
end

We are ready now..

Ex Usage :  u = User.new(:avatar_url => 'http://www.facebook.com/profile/pic')

Good luck :)


No comments:

Post a Comment