Created
June 14, 2012 07:51
-
-
Save jeromelefeuvre/2928860 to your computer and use it in GitHub Desktop.
Module for active Paperclip Url Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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