Sha256: 9b5da33144ba5ee9ff0d7ec27e2dfca1383f3fd688f8729cf56c24b7cb2349fd

Contents?: true

Size: 1.36 KB

Versions: 11

Compression:

Stored size: 1.36 KB

Contents

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

  # Returns a Tempfile containing the contents of the readable object.
  def to_tempfile
    tempfile = Tempfile.new("stream")
    tempfile.binmode
    self.stream_to(tempfile)
  end

  # 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.
  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
end

class IO
  include IOStream
end

%w( Tempfile StringIO ).each do |klass|
  if Object.const_defined? klass
    Object.const_get(klass).class_eval do
      include IOStream
    end
  end
end

Version data entries

11 entries across 11 versions & 3 rubygems

Version Path
kdmny-spree-0.0.1 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.8.4 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.8.5 vendor/plugins/paperclip/lib/paperclip/iostream.rb
dm-paperclip-2.1.4 lib/dm-paperclip/iostream.rb
spree-0.6.0 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.7.0 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.7.1 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.8.0 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.8.1 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.8.2 vendor/plugins/paperclip/lib/paperclip/iostream.rb
spree-0.8.3 vendor/plugins/paperclip/lib/paperclip/iostream.rb