Skip to content

Commit 2fe6687

Browse files
zmillmanJon Yurek
authored and
Jon Yurek
committed
Improve content type detector tests and logic
1 parent f1f446c commit 2fe6687

File tree

3 files changed

+15
-14
lines changed

3 files changed

+15
-14
lines changed

lib/paperclip/content_type_detector.rb

+9-9
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,12 @@ def detect
3131
SENSIBLE_DEFAULT
3232
elsif empty_file?
3333
EMPTY_TYPE
34-
elsif best_from_possible_types
35-
best_from_possible_types.content_type
34+
elsif types_matching_file.any?
35+
types_matching_file.first
36+
elsif official_types.any?
37+
official_types.first
38+
elsif possible_types.any?
39+
possible_types.first
3640
else
3741
type_from_file_command || SENSIBLE_DEFAULT
3842
end.to_s
@@ -53,19 +57,15 @@ def empty?
5357
end
5458

5559
def possible_types
56-
@possible_types ||= MIME::Types.type_for(@filename)
60+
@possible_types ||= MIME::Types.type_for(@filename).collect(&:content_type)
5761
end
5862

5963
def official_types
60-
@official_types ||= possible_types.reject {|type| type.content_type.match(/\/x-/) }
64+
@offical_types ||= possible_types.reject{|content_type| content_type.match(/\/x-/) }
6165
end
6266

6367
def types_matching_file
64-
possible_types.select{|type| type.content_type == type_from_file_command}
65-
end
66-
67-
def best_from_possible_types
68-
@best_from_possible_types ||= (types_matching_file.first || official_types.first || possible_types.first)
68+
@types_matching_file ||= possible_types.select{|content_type| content_type == type_from_file_command}
6969
end
7070

7171
def type_from_file_command

test/content_type_detector_test.rb

+6-5
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@ class ContentTypeDetectorTest < Test::Unit::TestCase
1414

1515
assert_equal "text/plain", Paperclip::ContentTypeDetector.new(tempfile.path).detect
1616
end
17-
18-
should 'return content type of uploaded file if it is an acceptable type' do
19-
@filename = fixture_file("sample_mpeg4.mp4")
17+
18+
should 'return content type of file if it is an acceptable type' do
19+
MIME::Types.stubs(:type_for).returns([MIME::Type.new('application/mp4'), MIME::Type.new('video/mp4'), MIME::Type.new('audio/mp4')])
20+
Paperclip.stubs(:run).returns("video/mp4")
21+
22+
@filename = "my_file.mp4"
2023
assert_equal "video/mp4", Paperclip::ContentTypeDetector.new(@filename).detect
2124
end
2225

@@ -41,7 +44,5 @@ class ContentTypeDetectorTest < Test::Unit::TestCase
4144
@filename = "/path/to/something"
4245
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect
4346
end
44-
45-
4647
end
4748
end

test/fixtures/sample_mpeg4.mp4

-240 KB
Binary file not shown.

0 commit comments

Comments
 (0)