Skip to content

Instantly share code, notes, and snippets.

@Lordnibbler
Created February 3, 2012 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lordnibbler/1729072 to your computer and use it in GitHub Desktop.
Save Lordnibbler/1729072 to your computer and use it in GitHub Desktop.
class Asset < ActiveRecord::Base
acts_as_paranoid
def upload_to_s3(file)
if file
#set content_type
content_type = determine_content_type(file)
self.content_type = content_type
#set filename
prefix = "/audio/" if content_type == "audio"
prefix = "/image/" if content_type == "image"
prefix = "/video/" if content_type == "video"
prefix = "/application/" if content_type == "application"
prefix = "/text/" if content_type == "text"
prefix ||= "/unknown/"
filename = "#{prefix}#{sanitize_filename(file.original_filename)}"
self.filename = filename
# self.filesize = number_to_human_size(File.size("#{file}"))
# self.thumbnail
# self.width
# self.height
begin
# determine content type
self.save if AWS::S3::S3Object.store(self.filename, file.read, S3_BUCKET, :access => "public_read")
rescue
render :text => "Couldn't upload"
end
else
#no attachment
return false
end
end
def determine_content_type(file)
MIME::Types.type_for(file.original_filename).first.content_type.split("/")[0]
end
def sanitize_filename(file_name)
just_filename = File.basename(file_name)
just_filename.sub(/[^\w\.\-]/, '_') #return relative path to file, with _ delimiter
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment