This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
/
abstract_adapter.rb
69 lines (56 loc) · 1.7 KB
/
abstract_adapter.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
require 'active_support/core_ext/module/delegation'
module Paperclip
class AbstractAdapter
OS_RESTRICTED_CHARACTERS = %r{[/:]}
attr_reader :content_type, :original_filename, :size
delegate :binmode, :binmode?, :close, :close!, :closed?, :eof?, :path, :readbyte, :rewind, :unlink, :to => :@tempfile
alias :length :size
def initialize(target, options = {})
@target = target
@options = options
end
def fingerprint
@fingerprint ||= begin
digest = @options.fetch(:hash_digest).new
File.open(path, "rb") do |f|
buf = ""
digest.update(buf) while f.read(16384, buf)
end
digest.hexdigest
end
end
def read(length = nil, buffer = nil)
@tempfile.read(length, buffer)
end
def inspect
"#{self.class}: #{self.original_filename}"
end
def original_filename=(new_filename)
return unless new_filename
@original_filename = new_filename.gsub(OS_RESTRICTED_CHARACTERS, "_")
end
def nil?
false
end
def assignment?
true
end
private
def destination
@destination ||= TempfileFactory.new.generate(@original_filename.to_s)
end
def copy_to_tempfile(src)
link_or_copy_file(src.path, destination.path)
destination
end
def link_or_copy_file(src, dest)
Paperclip.log("Trying to link #{src} to #{dest}")
FileUtils.ln(src, dest, force: true) # overwrite existing
@destination.close
@destination.open.binmode
rescue Errno::EXDEV, Errno::EPERM, Errno::ENOENT, Errno::EEXIST => e
Paperclip.log("Link failed with #{e.message}; copying link #{src} to #{dest}")
FileUtils.cp(src, dest)
end
end
end