Class: MemoryIO::IO
- Inherits:
-
Object
- Object
- MemoryIO::IO
- Defined in:
- lib/memory_io/io.rb
Overview
Main class to use MemoryIO.
Instance Attribute Summary collapse
- #stream ⇒ #pos, ... readonly
Instance Method Summary collapse
-
#initialize(stream) ⇒ IO
constructor
Instantiate an IO object.
-
#read(num_elements, from: nil, as: nil, force_array: false) ⇒ String, ...
Read and convert result into custom type/structure.
-
#rewind ⇒ 0
Set
stream
to the beginning. -
#write(objects, from: nil, as: nil) ⇒ void
Write to stream.
Constructor Details
#initialize(stream) ⇒ IO
Instantiate an MemoryIO::IO object.
18 19 20 |
# File 'lib/memory_io/io.rb', line 18 def initialize(stream) @stream = stream end |
Instance Attribute Details
#stream ⇒ #pos, ... (readonly)
9 10 11 |
# File 'lib/memory_io/io.rb', line 9 def stream @stream end |
Instance Method Details
#read(num_elements, from: nil, as: nil, force_array: false) ⇒ String, ...
Note:
This method’s arguments and return value are different with ::IO#read. Check documents and examples.
Read and convert result into custom type/structure.
103 104 105 106 107 108 109 110 111 112 |
# File 'lib/memory_io/io.rb', line 103 def read(num_elements, from: nil, as: nil, force_array: false) stream.pos = from if from return stream.read(num_elements) if as.nil? conv = to_proc(as, :read) # TODO: handle eof ret = Array.new(num_elements) { conv.call(stream) } ret = ret.first if num_elements == 1 && !force_array ret end |
#rewind ⇒ 0
Set stream
to the beginning. i.e. invoke stream.pos = 0.
177 178 179 |
# File 'lib/memory_io/io.rb', line 177 def rewind stream.pos = 0 end |
#write(objects, from: nil, as: nil) ⇒ void
This method returns an undefined value.
Write to stream.
164 165 166 167 168 169 170 171 |
# File 'lib/memory_io/io.rb', line 164 def write(objects, from: nil, as: nil) stream.pos = from if from as ||= objects.class if objects.class.ancestors.include?(MemoryIO::Types::Type) return stream.write(objects) if as.nil? conv = to_proc(as, :write) Array(objects).map { |o| conv.call(stream, o) } end |