Storing image using open URI and paperclip having size less than 10kb

Mohit Jain picture Mohit Jain · Jun 9, 2011 · Viewed 11.6k times · Source

I want to import some icons from my old site. The size of those icons is less than 10kb. So when I am trying to import the icons its returning stringio.txt file.

require "open-uri"
class Category < ActiveRecord::Base
   has_attached_file :icon,  :path => ":rails_root/public/:attachment/:id/:style/:basename.:extension"
  def icon_from_url(url)
    self.icon = open(url)
   end    
end

In rake task.

   category = Category.new
   category.icon_from_url "https://xyz.com/images/dog.png"
   category.save

Answer

Kevin Sylvestre picture Kevin Sylvestre · Jun 13, 2011

Try:

def icon_from_url(url)
  extname = File.extname(url)
  basename = File.basename(url, extname)

  file = Tempfile.new([basename, extname])
  file.binmode

  open(URI.parse(url)) do |data|  
    file.write data.read
  end

  file.rewind

  self.icon = file
end