Skip to content

Instantly share code, notes, and snippets.

@mbj
Created October 6, 2011 15:09
Show Gist options
  • Save mbj/1267638 to your computer and use it in GitHub Desktop.
Save mbj/1267638 to your computer and use it in GitHub Desktop.
property :id, Serial
property :name, String, required: true
property :size, Integer
property :type, String
property :content, Binary, lazy: true, length: 1..209715200
property :uri, URI
property :created_at, DateTime
property :updated_at, DateTime
belongs_to :folder, model: Filemanager::Folder
before :save, :create_uri
def self.copy( files, folder_id )
files.each do |file|
_content = file.content.force_encoding 'binary'
create({
name: file.name,
size: file.size,
type: file.type,
content: _content,
folder_id: folder_id
})
end
end
def self.from_uploaded( files, folder )
success, errors = [], []
files.to_a.each do |file|
size = file[:tempfile].size
content = file[:tempfile].read(size)
unless content.bytesize == size
raise "truncation"
end
f = new({
name: file[:filename],
type: file[:type],
content: content,
size: size,
folder: folder
})
file[:tempfile].delete
if f.valid?
f.save
attrs = f.attributes
attrs.delete( :content )
success.push( attr )
else
errors.push( { file: f.name,
errors: f.errors.full_messages } )
end # if
end # files each
{ success: success, errors: errors }
end
def create_uri
ancestors = folder.ancestors
ancestors.shift # remove root
_uri = ancestors.map{ |a| a.name.strip }.join('/')
self.uri = "#{SLUG}#{_uri}/#{name}".downcase.gsub(/[^\w\/\.]/, '_')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment