@@ -67,14 +67,20 class Attachment < ActiveRecord::Base | |||
|
67 | 67 | nil |
|
68 | 68 | end |
|
69 | 69 | |
|
70 |
# Cop |
|
|
70 | # Copies the temporary file to its final location | |
|
71 | # and computes its MD5 hash | |
|
71 | 72 | def before_save |
|
72 | 73 | if @temp_file && (@temp_file.size > 0) |
|
73 | 74 | logger.debug("saving '#{self.diskfile}'") |
|
75 | md5 = Digest::MD5.new | |
|
74 | 76 | File.open(diskfile, "wb") do |f| |
|
75 | f.write(@temp_file.read) | |
|
77 | buffer = "" | |
|
78 | while (buffer = @temp_file.read(8192)) | |
|
79 | f.write(buffer) | |
|
80 | md5.update(buffer) | |
|
81 | end | |
|
76 | 82 | end |
|
77 |
self.digest = |
|
|
83 | self.digest = md5.hexdigest | |
|
78 | 84 | end |
|
79 | 85 | # Don't save the content type if it's longer than the authorized length |
|
80 | 86 | if self.content_type && self.content_type.length > 255 |
@@ -143,11 +149,4 private | |||
|
143 | 149 | end |
|
144 | 150 | df |
|
145 | 151 | end |
|
146 | ||
|
147 | # Returns the MD5 digest of the file at given path | |
|
148 | def self.digest(filename) | |
|
149 | File.open(filename, 'rb') do |f| | |
|
150 | Digest::MD5.hexdigest(f.read) | |
|
151 | end | |
|
152 | end | |
|
153 | 152 | end |
@@ -22,6 +22,19 class AttachmentTest < Test::Unit::TestCase | |||
|
22 | 22 | |
|
23 | 23 | def setup |
|
24 | 24 | end |
|
25 | ||
|
26 | def test_create | |
|
27 | a = Attachment.new(:container => Issue.find(1), | |
|
28 | :file => test_uploaded_file("testfile.txt", "text/plain"), | |
|
29 | :author => User.find(1)) | |
|
30 | assert a.save | |
|
31 | assert_equal 'testfile.txt', a.filename | |
|
32 | assert_equal 59, a.filesize | |
|
33 | assert_equal 'text/plain', a.content_type | |
|
34 | assert_equal 0, a.downloads | |
|
35 | assert_equal Digest::MD5.hexdigest(test_uploaded_file("testfile.txt", "text/plain").read), a.digest | |
|
36 | assert File.exist?(a.diskfile) | |
|
37 | end | |
|
25 | 38 | |
|
26 | 39 | def test_diskfilename |
|
27 | 40 | assert Attachment.disk_filename("test_file.txt") =~ /^\d{12}_test_file.txt$/ |
@@ -30,8 +43,4 class AttachmentTest < Test::Unit::TestCase | |||
|
30 | 43 | assert_equal 'f8139524ebb8f32e51976982cd20a85d', Attachment.disk_filename("test_accentué")[13..-1] |
|
31 | 44 | assert_equal 'cbb5b0f30978ba03731d61f9f6d10011', Attachment.disk_filename("test_accentué.ça")[13..-1] |
|
32 | 45 | end |
|
33 | ||
|
34 | def test_digest | |
|
35 | assert_equal '1478adae0d4eb06d35897518540e25d6', Attachment.digest(Test::Unit::TestCase.fixture_path + "/files/testfile.txt") | |
|
36 | end | |
|
37 | 46 | end |
General Comments 0
You need to be logged in to leave comments.
Login now