Skip to content

Instantly share code, notes, and snippets.

@tjh
Created February 9, 2011 13:05
Show Gist options
  • Save tjh/818437 to your computer and use it in GitHub Desktop.
Save tjh/818437 to your computer and use it in GitHub Desktop.
# Monkeypatch paperclip to handle local file attachment. Didn't add this to
# the class itself as we only need local loading during the population
AssetItem.class_eval do
require 'open-uri'
attr_accessor :source_filename, :source_url, :source_path, :existing_cache_file, :new_cache_file
before_validation :import_source_file, :if => :source_filename_provided?
private
def source_filename_provided?
!self.source_filename.blank?
end
def import_source_file
create_missing_folders
do_download_remote_file unless existing_cache_file
self.item = do_import_local_file
end
def do_import_local_file
io = Paperclip::Tempfile.new(source_filename)
io.write existing_cache_file.read unless existing_cache_file.nil?
io.size > 0 ? io : nil
end
def do_download_remote_file
uri = URI.parse(remote_url)
Net::HTTP.start(uri.host) do |http|
response = http.get(uri.request_uri)
File.open(localpath, "w+") do |file|
file.write response.body
end
end
end
def existing_cache_file
begin
File.open(localpath, "r")
rescue
nil
end
end
def create_missing_folders
FileUtils.makedirs File.dirname(localpath)
end
def localpath
File.join ::Rails.root.to_s, "#{source_path}/#{source_filename}"
end
def remote_url
"#{source_url}/#{source_filename}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment