/
resource_uploader.rb
79 lines (62 loc) · 1.74 KB
/
resource_uploader.rb
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
72
73
74
75
76
77
78
79
# frozen_string_literal: true
require "marcel"
class ResourceUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
before :process, :check_content_type!
process :fix_exif_rotation, if: :image?
process :strip, if: :image?
def content_type_allowlist
[%r{image/}, %r{audio/}, %r{video/}, "text/plain"]
end
def store_dir
"files/#{model.class.to_s.underscore}/#{model.id}"
end
version :thumb, if: :image? do
process dynamic_resize_to_fit: :thumb
end
version :medium, if: :image? do
process dynamic_resize_to_fit: :medium
end
version :avatar, if: :image? do
process dynamic_resize_to_fit: :avatar
end
def dynamic_resize_to_fit(size)
resize_setting = model.blog.send("image_#{size}_size").to_i
resize_to_fit(resize_setting, resize_setting)
end
def strip
manipulate! do |img|
img.strip
img = yield(img) if block_given?
img
end
end
def fix_exif_rotation
manipulate! do |img|
img.auto_orient
img = yield(img) if block_given?
img
end
end
def image?(new_file)
content_type = new_file.content_type
content_type&.include?("image")
end
def check_content_type!(new_file)
detected_type = if image? new_file
file_content_content_type(new_file)
else
file_content_type(new_file)
end
if detected_type != new_file.content_type
raise CarrierWave::IntegrityError, "has MIME type mismatch"
end
end
private
def file_content_content_type(new_file)
Marcel::MimeType.for Pathname.new(new_file.path)
end
def file_content_type(new_file)
Marcel::MimeType.for Pathname.new(new_file.path), name: new_file.filename
end
end