Module: IOStream

Included in:
IO
Defined in:
lib/paperclip/iostream.rb

Overview

Provides method that can be included on File-type objects (IO, StringIO, Tempfile, etc) to allow stream copying and Tempfile conversion.

Instance Method Summary collapse

Instance Method Details

#stream_to(path_or_file, in_blocks_of = 8192) ⇒ Object

Copies one read-able object from one place to another in blocks, obviating the need to load the whole thing into memory. Defaults to 8k blocks. If this module is included in both StringIO and Tempfile, then either can have its data copied anywhere else without typing worries or memory overhead worries. Returns a File if a String is passed in as the destination and returns the IO or Tempfile as passed in if one is sent as the destination.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/paperclip/iostream.rb', line 18

def stream_to path_or_file, in_blocks_of = 8192
  dstio = case path_or_file
          when String   then File.new(path_or_file, "wb+")
          when IO       then path_or_file
          when Tempfile then path_or_file
          end
  buffer = ""
  self.rewind
  while self.read(in_blocks_of, buffer) do
    dstio.write(buffer)
  end
  dstio.rewind
  dstio
end

#to_tempfileObject

Returns a Tempfile containing the contents of the readable object.



6
7
8
9
10
11
# File 'lib/paperclip/iostream.rb', line 6

def to_tempfile
  name = respond_to?(:original_filename) ? original_filename : (respond_to?(:path) ? path : "stream")
  tempfile = Paperclip::Tempfile.new("stream" + File.extname(name))
  tempfile.binmode
  self.stream_to(tempfile)
end