forked from patshaughnessy/paperclip
-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate_attachment_content_type_matcher.rb
65 lines (53 loc) · 1.73 KB
/
validate_attachment_content_type_matcher.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
module Paperclip
module Shoulda
module Matchers
def validate_attachment_content_type name
ValidateAttachmentContentTypeMatcher.new(name)
end
class ValidateAttachmentContentTypeMatcher
def initialize attachment_name
@attachment_name = attachment_name
end
def allowing *types
@allowed_types = types.flatten
self
end
def rejecting *types
@rejected_types = types.flatten
self
end
def matches? subject
@subject = subject
@allowed_types && @rejected_types &&
allowed_types_allowed? && rejected_types_rejected?
end
def failure_message
"Content types #{@allowed_types.join(", ")} should be accepted" +
" and #{@rejected_types.join(", ")} rejected by #{@attachment_name}"
end
def negative_failure_message
"Content types #{@allowed_types.join(", ")} should be rejected" +
" and #{@rejected_types.join(", ")} accepted by #{@attachment_name}"
end
def description
"validate the content types allowed on attachment #{@attachment_name}"
end
protected
def allow_types?(types)
types.all? do |type|
file = StringIO.new(".")
file.content_type = type
(subject = @subject.new).attachment_for(@attachment_name).assign(file)
subject.valid? && subject.errors.on(:"#{@attachment_name}_content_type").blank?
end
end
def allowed_types_allowed?
allow_types?(@allowed_types)
end
def rejected_types_rejected?
not allow_types?(@rejected_types)
end
end
end
end
end