refactored a bit & tested thumbnails creation

This commit is contained in:
Régis Hanol
2013-06-17 02:46:42 +02:00
parent cc9e0ec80a
commit 510bac4b27
6 changed files with 67 additions and 27 deletions

View File

@ -1,15 +1,39 @@
require "digest/sha1"
class OptimizedImage < ActiveRecord::Base
belongs_to :upload
def self.create_for(upload_id, path)
image_info = FastImage.new(path)
OptimizedImage.new({
upload_id: upload_id,
sha: Digest::SHA1.file(path).hexdigest,
ext: File.extname(path),
width: image_info.size[0],
height: image_info.size[1]
})
def self.create_for(upload, width=nil, height=nil)
@image_sorcery_loaded ||= require "image_sorcery"
original_path = "#{Rails.root}/public#{upload.url}"
# create a temp file with the same extension as the original
temp_file = Tempfile.new(["discourse", File.extname(original_path)])
temp_path = temp_file.path
# do the resize when there is both dimensions
if width && height && ImageSorcery.new(original_path).convert(temp_path, resize: "#{width}x#{height}")
image_info = FastImage.new(temp_path)
thumbnail = OptimizedImage.new({
upload_id: upload.id,
sha: Digest::SHA1.file(temp_path).hexdigest,
ext: File.extname(temp_path),
width: image_info.size[0],
height: image_info.size[1]
})
# make sure the directory exists
FileUtils.mkdir_p Pathname.new(thumbnail.path).dirname
# move the temp file to the right location
File.open(thumbnail.path, "wb") do |f|
f.write temp_file.read
end
end
# close && remove temp file
temp_file.close
temp_file.unlink
thumbnail
end
def url