|
1 | 1 | # Provides method that can be included on File-type objects (IO, StringIO, Tempfile, etc) to allow stream copying
|
2 | 2 | # and Tempfile conversion.
|
3 | 3 | module IOStream
|
4 |
| - |
5 | 4 | # Returns a Tempfile containing the contents of the readable object.
|
6 |
| - def to_tempfile |
7 |
| - name = respond_to?(:original_filename) ? original_filename : (respond_to?(:path) ? path : "stream") |
| 5 | + def to_tempfile(object) |
| 6 | + return object.to_tempfile if object.respond_to?(:to_tempfile) |
| 7 | + name = object.respond_to?(:original_filename) ? object.original_filename : (object.respond_to?(:path) ? object.path : "stream") |
8 | 8 | tempfile = Paperclip::Tempfile.new(["stream", File.extname(name)])
|
9 | 9 | tempfile.binmode
|
10 |
| - self.stream_to(tempfile) |
| 10 | + stream_to(object, tempfile) |
11 | 11 | end
|
12 | 12 |
|
13 | 13 | # Copies one read-able object from one place to another in blocks, obviating the need to load
|
14 |
| - # the whole thing into memory. Defaults to 8k blocks. If this module is included in both |
15 |
| - # StringIO and Tempfile, then either can have its data copied anywhere else without typing |
16 |
| - # worries or memory overhead worries. Returns a File if a String is passed in as the destination |
17 |
| - # and returns the IO or Tempfile as passed in if one is sent as the destination. |
18 |
| - def stream_to path_or_file, in_blocks_of = 8192 |
| 14 | + # the whole thing into memory. Defaults to 8k blocks. Returns a File if a String is passed |
| 15 | + # in as the destination and returns the IO or Tempfile as passed in if one is sent as the destination. |
| 16 | + def stream_to object, path_or_file, in_blocks_of = 8192 |
19 | 17 | dstio = case path_or_file
|
20 | 18 | when String then File.new(path_or_file, "wb+")
|
21 | 19 | when IO then path_or_file
|
22 | 20 | when Tempfile then path_or_file
|
23 | 21 | end
|
24 | 22 | buffer = ""
|
25 |
| - self.rewind |
26 |
| - while self.read(in_blocks_of, buffer) do |
| 23 | + object.rewind |
| 24 | + while object.read(in_blocks_of, buffer) do |
27 | 25 | dstio.write(buffer)
|
28 | 26 | end
|
29 | 27 | dstio.rewind
|
30 | 28 | dstio
|
31 | 29 | end
|
32 | 30 | end
|
33 | 31 |
|
34 |
| -class IO #:nodoc: |
35 |
| - include IOStream |
36 |
| -end |
37 |
| - |
38 |
| -%w( Tempfile StringIO ).each do |klass| |
39 |
| - if Object.const_defined? klass |
40 |
| - Object.const_get(klass).class_eval do |
41 |
| - include IOStream |
42 |
| - end |
43 |
| - end |
44 |
| -end |
45 |
| - |
46 | 32 | # Corrects a bug in Windows when asking for Tempfile size.
|
47 | 33 | if defined? Tempfile
|
48 | 34 | class Tempfile
|
|
0 commit comments