image.rb
2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require "mini_magick"
module Kanjai
class Image < ActiveRecord::Base
acts_as_taggable
belongs_to :object, polymorphic: true, optional: true
IMAGE_MIME_TYPE = ['image/bmp', 'image/gif', 'image/jpeg', 'image/pipeg', 'image/svg+xml', 'image/png']
PDF_MIME_TYPE = ['application/pdf']
# has_attached_file :image,
# :styles => {:mini => '200x200>'},
# :path => ":object_type/:object_id/images/:id/:style/:basename.:extension",
# :s3_permissions => :public_read,
# :url => ':s3_domain_url'
default_scope { order('created_at') }
after_destroy :clear_storage
def self.get_image_file_path
"images/"
end
def self.get_thumb_image_file_path
"thumbnailImage/"
end
def resize!
if image_link.present? && file_type.present? && Kanjai::Image::IMAGE_MIME_TYPE.include?(file_type)
begin
obj = S3_BUCKET.object(image_link.split('/')[3..-1].join('/'))
img = MiniMagick::Image.open(obj.public_url)
img.resize "400x400"
img.format "png"
thumb_image_link = image_link.split('/')[3..-1].join('/').gsub(Kanjai::Image.get_image_file_path, Kanjai::Image.get_thumb_image_file_path)
obj = S3_BUCKET.put_object({
acl: 'public-read',
body: img.to_blob,
content_type: file_type,
key: thumb_image_link
})
update_column(:thumb_image_link, obj.public_url)
rescue
end
end
end
def preview_link
thumb_image_link || image_link
end
private
def clear_storage
if image_link.present?
obj = S3_BUCKET.object(image_link.split('/')[3..-1].join('/'))
obj.delete
end
if thumb_image_link.present?
obj = S3_BUCKET.object(thumb_image_link.split('/')[3..-1].join('/'))
obj.delete
end
end
end
end