Class: ThreadIO
- Inherits:
-
Object
- Object
- ThreadIO
- Defined in:
- lib/thread_io.rb
Overview
this class loads the contents of a file using a Thread so that it’s running outside your main Thread.
Usage:
tio = ThreadIO.new.read('/tmp/a_large_file.txt') # read a file
... do other stuff ...
# optional loop until the file is read
loop do
breadk if tio.ready?
sleep 1
end
tio.string # contains the contents of the file as one large String
Instance Attribute Summary collapse
-
#string ⇒ Object
readonly
Returns the value of attribute string.
Instance Method Summary collapse
-
#initialize ⇒ ThreadIO
constructor
A new instance of ThreadIO.
-
#read(path) ⇒ Object
this method returns immediately and loads the file in the background.
- #ready? ⇒ Boolean
Constructor Details
#initialize ⇒ ThreadIO
Returns a new instance of ThreadIO.
18 19 20 21 |
# File 'lib/thread_io.rb', line 18 def initialize @ready = false @string = nil end |
Instance Attribute Details
#string ⇒ Object (readonly)
Returns the value of attribute string.
16 17 18 |
# File 'lib/thread_io.rb', line 16 def string @string end |
Instance Method Details
#read(path) ⇒ Object
this method returns immediately and loads the file in the background
path: the path to the file you want to read.
26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/thread_io.rb', line 26 def read(path) @ready = false Thread.new do @string = nil @string = IO.read(path) @ready = true nil end nil end |
#ready? ⇒ Boolean
39 40 41 |
# File 'lib/thread_io.rb', line 39 def ready? @ready end |