Upload image by Paperclip using url, by dynamic column management


Upload image in rails using Paperclip supporting dynamic column:

Create Module: app/models/base/image.rb


require 'open-uri'
module Base::Image
  module ClassMethods
  end

  module InstanceMethods
    #Uploads image on basic of Url
    #Parameters: column -> column name in string , url-> url of image 
    def upload_image(column, url)
      begin
        url.gsub!('www.','http://') #If www is not working then enable this option
        url = URI.decode(url.to_s) #If URLS contain spaces in image name
        io = open(URI.escape(url))

        if io
          def io.original_filename; base_uri.path.split('/').last; end
          io.original_filename.blank? ? nil : io
          eval("self.#{column} = io")
        end
        self.save(:validate => false)
      rescue Exception => e
        logger.info "EXCEPTION# #{e.message}"
      end
    end
  end

  def self.included(receiver)
      receiver.extend         ClassMethods
      receiver.send :include, InstanceMethods
  end
end

Note:
url = URI.decode(url.to_s) #If URLS contain spaces in image name, Note that I’ve used “url.to_s” because I’m reading from Nokogiri XML parser which return node’s attributes in object form and you have to convert them to string.

Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: ,
Posted in paperclip, Ruby Little Codes, Ruby on Rails
One comment on “Upload image by Paperclip using url, by dynamic column management
  1. Uploading image through url is very simple in carrierwave.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

StackOverFlow
Categories
Archives
%d bloggers like this: