Class: ThreadIO

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initializeThreadIO

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

#linesObject (readonly)

Returns the value of attribute lines.



16
17
18
# File 'lib/thread_io.rb', line 16

def lines
  @lines
end

#stringObject (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

Returns:

  • (Boolean)


54
55
56
# File 'lib/thread_io.rb', line 54

def ready?
  @ready
end