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.



44
45
46
# File 'lib/omnizip/io/source.rb', line 44

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:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/omnizip/io/source.rb', line 29

def self.for(input)
  case input
  when ::IO, ::StringIO, ::Tempfile then new(input)
  when String then StringSource.new(input)
  else
    # allowed: boundary validation; duck-typing ends at this adapter
    unless input.respond_to?(:read)
      raise ArgumentError,
            "Cannot adapt #{input.inspect} to Omnizip::IO::Source"
    end

    new(input)
  end
end

Instance Method Details

#closeObject



59
60
61
62
# File 'lib/omnizip/io/source.rb', line 59

def close
  # allowed: wrapped object may be a read-only duck with no close
  @io.close if @io.respond_to?(:close)
end

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

Delegate reading to the underlying IO-like object.



49
50
51
52
53
54
55
56
57
# File 'lib/omnizip/io/source.rb', line 49

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