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
break if tio.ready?
sleep 1
end
tio.string # contains the contents of the file as one large String
Instance Attribute Summary collapse
-
#lines ⇒ Object
readonly
Returns the value of attribute lines.
-
#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.
- #read_lines(path) ⇒ Object
- #ready? ⇒ Boolean
Constructor Details
#initialize ⇒ ThreadIO
Returns a new instance of ThreadIO.
19 20 21 22 23 |
# File 'lib/thread_io.rb', line 19 def initialize @ready = false @string = nil @lines = nil end |
Instance Attribute Details
#lines ⇒ Object (readonly)
Returns the value of attribute lines.
16 17 18 |
# File 'lib/thread_io.rb', line 16 def lines @lines end |
#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.
28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/thread_io.rb', line 28 def read(path) @ready = false Thread.new do @string = nil @string = IO.read(path) @ready = true nil end nil end |
#read_lines(path) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/thread_io.rb', line 41 def read_lines(path) @ready = false Thread.new do @lines = [] File.open(path, 'r') {|f| f.each_line{|l| @lines << l.chomp } } @ready = true nil end nil end |
#ready? ⇒ Boolean
54 55 56 |
# File 'lib/thread_io.rb', line 54 def ready? @ready end |