Class: Omnizip::IO::Source

Inherits:
Object
  • Object
show all
Defined in:
lib/omnizip/io/source.rb

Overview

Polymorphic adapter for "things we can read bytes from".

Callers that previously did:

data = input.respond_to?(:read) ? input.read : File.binread(input)

should now do:

data = Omnizip::IO::Source.for(input).read

Adapters:

  • +IO+/+StringIO+/+Tempfile+ → wrapped as-is
  • String → treated as a file path; read with File.binread unless the string contains no NUL bytes and does not exist on disk, in which case it is treated as literal data
  • Object responding to :read → delegated to

Defined Under Namespace

Classes: StringSource

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io) ⇒ Source

Returns a new instance of Source.



40
41
42
# File 'lib/omnizip/io/source.rb', line 40

def initialize(io)
  @io = io
end

Class Method Details

.for(input) ⇒ Source

Build a Source wrapper appropriate for input.

Parameters:

  • input (IO, StringIO, String, #read)

    the read target

Returns:



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/omnizip/io/source.rb', line 26

def self.for(input)
  case input
  when ::IO, ::StringIO, ::Tempfile then new(input)
  when String then StringSource.new(input)
  else
    unless input.respond_to?(:read)
      raise ArgumentError,
            "Cannot adapt #{input.inspect} to Omnizip::IO::Source"
    end

    new(input)
  end
end

Instance Method Details

#closeObject



55
56
57
# File 'lib/omnizip/io/source.rb', line 55

def close
  @io.close if @io.respond_to?(:close)
end

#read(length = nil, outbuf = nil) ⇒ Object

Delegate reading to the underlying IO-like object.



45
46
47
48
49
50
51
52
53
# File 'lib/omnizip/io/source.rb', line 45

def read(length = nil, outbuf = nil)
  if length.nil?
    @io.read
  elsif outbuf
    @io.read(length, outbuf)
  else
    @io.read(length)
  end
end