Skip to content

Instantly share code, notes, and snippets.

@knewter
Created December 3, 2008 21:00
Show Gist options
  • Save knewter/31689 to your computer and use it in GitHub Desktop.
Save knewter/31689 to your computer and use it in GitHub Desktop.
require 'zip/zip'
require 'zip/zipfilesystem'
require 'guid'
class AlbumZipImporter
attr_accessor :file, :photos, :album, :guid, :unzip_dir
def initialize album_name, file
@file = file
@photos = []
@album = Album.find_or_create_by_name album_name
@guid = Guid.new.hexdigest
@unzip_dir = "#{RAILS_ROOT}/tmp/#{@guid}"
# Extract the files into a tmp directory based on @guid
set_photos
# Remove everything from the album and replace it with the files, in the
# order they appear in the zip file
create_album
# Destroy the tmp/guid directory recursively
destroy_tmp_files
end
def destroy_tmp_files
puts "in destroy_tmp_files"
`rm -fr #{@unzip_dir}`
end
def set_photos
puts "in set_photos"
ordered_files = []
Zip::ZipFile.open(@file){|zf|
zf.each{|file|
ordered_files << file
}
ordered_files = ordered_files.sort_by{|file| file.name}
ordered_files.each{|file|
puts file.name
fpath = File.join(@unzip_dir, file.name)
FileUtils.mkdir_p(File.dirname(fpath))
# unzip the file into the tmp dir, then add its path into the photos array
zf.extract(file, fpath)
@photos << fpath
}
}
end
def create_album
@album.photos.map(&:destroy)
@photos.each do |photo|
p = Photo.new
p.image = File.open(photo)
@album.photos << p
end
album.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment