Class: Tins::TempIO::Enum

Inherits:
Enumerator
  • Object
show all
Includes:
Tins::TempIO
Defined in:
lib/tins/temp_io_enum.rb

Overview

A streaming enumerator that reads file content in configurable chunks from temporary files.

This class provides an efficient way to process large files without loading them entirely into memory. It creates a temporary file from the provided content generator and yields data in fixed-size chunks.

Instance Method Summary collapse

Methods included from Tins::TempIO

#temp_io

Constructor Details

#initialize(chunk_size: 2 ** 16, filename: nil, &content_proc) ⇒ Enumerator

This method creates an enumerator that yields chunks of data from a temporary file generated from the provided content proc. It’s designed for streaming large files efficiently (to a user’s web browser for example) by reading them in fixed-size chunks rather than loading everything into memory.

file enumerator eventually having #filename defined as the parameter filename.

Parameters:

  • chunk_size (Integer) (defaults to: 2 ** 16)

    the size of each chunk to read from the

  • filename (String, nil) (defaults to: nil)

    optional filename to associate with the

  • content_proc (Proc)

    a block that generates file content



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/tins/temp_io_enum.rb', line 27

def initialize(chunk_size: 2 ** 16, filename: nil, &content_proc)
  content_proc or raise ArgumentError, 'need a content proc as block argument'
  super() do |y|
    temp_io(name: 'some-stream', content: content_proc) do |file|
      until file.eof?
        y.yield file.read(chunk_size)
      end
    end
  end.tap do |enum|
    if filename
      enum.define_singleton_method(:filename) do
        filename
      end
    end
  end
end