Skip to content

Instantly share code, notes, and snippets.

@adjohu
Created February 9, 2012 10:22
Show Gist options
  • Save adjohu/1779088 to your computer and use it in GitHub Desktop.
Save adjohu/1779088 to your computer and use it in GitHub Desktop.
class Image
include DataMapper::Resource
include FilesHelper
belongs_to :gallery, :required => true
has 1, :user, :through => :gallery
# property <name>, <type>
property :id, Serial
property :name, String
property :filename, String
property :created_on, DateTime
def self.in_gallery(gallery_id)
if(gallery = Gallery.get(gallery_id))
images = Image.all(:gallery => gallery)
end
end
def src
self.user.get_web_file_dir + "/" + filename
end
def path(filename = @filename)
file_dir = self.user.get_file_dir
File.join(file_dir, filename)
end
def upload(file)
require 'fileutils'
# Get upload path and create it if needed
file_dir = self.user.get_file_dir
FileUtils.mkdir_p(file_dir)
filename = file.original_filename
tmpfile = file.tempfile
# Write the file with a unique filename
loop do
begin
file_path = path(filename)
File.open(file_path, File::CREAT | File::EXCL | File::WRONLY) do |file|
file.write(tmpfile.read)
end
break
rescue Errno::EEXIST
puts "File exists #{filename}"
filename = increment(filename)
redo
end
end
self.filename = filename
self.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment