Created
August 2, 2010 20:29
-
-
Save freegenie/505256 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Asset | |
include MongoMapper::Document | |
plugin Joint | |
# Next time use '#' hash mark to crop images. i.e. #200x250 | |
Thumbs = { :detail => "440x300>", :medium => "220x150>", :little => "100x60>", :highlights => 'crop-200x250' } | |
attachment :file | |
key :name, String | |
key :txp_id, Integer | |
timestamps! | |
many :thumbnails, :foreign_key => :asset_id, :dependent => :destroy | |
many :primary_image_for, :foreign_key => :primary_image_id, :class_name => "Content" | |
validates_presence_of :file_size | |
before_validation :assign_asset_name | |
after_save :make_thumbs, :if => :make_thumbs? | |
def assign_asset_name | |
self.name = self.file_name if self.name.blank? | |
end | |
def make_thumbs? | |
is_image? | |
end | |
def is_image? | |
self.file_type.scan(/image/).size > 0 | |
end | |
# Please ignore the cropping code, need to rewrite that. | |
def make_thumbs | |
original = Magick::Image.from_blob(Asset.find(self.id).file.read).first | |
self.thumbnails = [] | |
Thumbs.each do |key, value| | |
new_image = original.clone | |
if value =~ /crop-/ | |
values = value.scan /(\d+)x(\d+)/ | |
new_image.crop!(Magick::CenterGravity, values.first[0].to_i, values.first[1].to_i ) | |
else | |
new_image.change_geometry(value) {|x,y,image| image.resize!(x,y) } | |
end | |
path = File.join(Rails.root, 'tmp', "#{key}-#{self.file_name}" ) | |
ff = File.open( path , 'w+') | |
ff.write(new_image.to_blob) | |
self.thumbnails << Thumbnail.new(:format => key.to_s, :file => ff ) | |
FileUtils.rm path | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment