Skip to content

Instantly share code, notes, and snippets.

@teamon
Created November 18, 2008 15:39
Show Gist options
  • Save teamon/26151 to your computer and use it in GitHub Desktop.
Save teamon/26151 to your computer and use it in GitHub Desktop.
= fieldset :legend => "Images:" do
- @product.max_attachments_size.times do |i|
%p
- if a = @product.attachments[i]
= file_field :name => "product[attachments][#{a.id}][data]", :label => a.filename
= check_box :name => "product[attachments][#{a.id}][delete]", :label => "Delete?".t
- else
= file_field :name => "product[attachments][new][]", :label => "Image %d:".t(i+1)
module Attachable
def self.included(base)
base.class_eval do
validates_with_method :validate_attachments
end
end
def attachments
@attachments ||= attachment_class.all(:attachable_type => self.class, :attachable_id => self.id)
end
def validate_attachments
attachments.each_with_index do |att, i|
if att.valid?
att.save
else
return [false, "Images are invalid".t]
end
end
true
end
def attachments=(set)
Merb.logger.d set
attachments.each do |att|
a = set[att.id.to_s]
if a[:delete]
att.destroy
elsif !(data = a[:data]).empty?
att.update_file(data)
end
end
(max_attachments_size - attachments.size).times do |i|
unless (file = set[:new][i]).blank?
att = attachment_class.new :attachable_type => self.class,
:attachable_id => self.id,
:file => file
attachments << att
end
end
end
end
require "ftools"
class Attachment
include DataMapper::Resource
attr_accessor :tempfile
property :id, Serial
property :filename, String
property :content_type, String
property :size, Integer
property :attachable_id, Integer
property :attachable_type, String
def url
"/uploads/#{id}/#{filename}"
end
before :destroy, :delete_files
after :create, :copy_files
def delete_files
FileUtils.remove_dir("public/uploads/#{id}")
end
def update_file(file)
orig_filename = filename
self.file = file
if valid?
delete_files
save
copy_files
true
else
self.filename = orig_filename
false
end
end
def file=(file)
self.filename = file[:filename]
self.content_type = file[:content_type]
self.size = file[:size]
self.tempfile = file[:tempfile]
end
def copy_files
File.makedirs("public/uploads/#{id}")
FileUtils.mv(tempfile.path, "public/uploads/#{id}/#{filename}")
end
end
class Product
include DataMapper::Resource
include Attachable
def max_attachments_size
4
end
def attachment_class
Image
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment