Skip to content

Instantly share code, notes, and snippets.

@jeromelefeuvre
Created June 14, 2012 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromelefeuvre/2928860 to your computer and use it in GitHub Desktop.
Save jeromelefeuvre/2928860 to your computer and use it in GitHub Desktop.
Module for active Paperclip Url Upload
# In your model after declaring your attachments, add:
# include HasPaperclipUrlUpload
# Thanks to https://gist.github.com/1502777
require 'open-uri'
module HasPaperclipUrlUpload
def self.included(base)
base.attachment_definitions.collect{|key, values| key}.each do |key|
base.class_eval <<-EOS
attr_accessor :#{key}_url
before_validation :download_remote_#{key}, :if => :#{key}_url_provided?
validates_presence_of :#{key}_remote_url, :if => :#{key}_url_provided?, :message => 'is invalid or inaccessible'
def #{key}_remote_url
if self.#{key}_url.present?
self.#{key}_url
else
self.#{key}.url if !new_record? and self.#{key}?
end
end
def #{key}_remote_url=(remote_url)
self.#{key}_url = remote_url
end
private
def #{key}_url_provided?
!self.#{key}_remote_url.blank?
end
def download_remote_#{key}
io = open(URI.parse(#{key}_url))
self.#{key}_file_name = io.base_uri.path.split('/').last
self.#{key} = io
rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)
end
EOS
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment