-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_queue.rb
More file actions
100 lines (93 loc) · 1.82 KB
/
file_queue.rb
File metadata and controls
100 lines (93 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#
#
# this code is made available under the MIT License (see MIT-LICENSE.txt)
# Copyright (c) 2010 Yuri Baranov <baranovu+gh@gmail.com>
#
# A quik and dirty IPC via the file
# each message is a single line terminated with \n
#
# May not be 100% bulletproof, but good enough for
# non-critical code for interactive experiments.
#
# Also, easier to implement and understand than, say, Drb-based
# or HTTP-server based solution
module SimpleFileQueue
class Reader
def initialize(filename)
@rfn=filename
@pos=0
end
def read
return nil unless open()
@fr.pos=@pos
result=readline
@pos=@fr.pos if result #advance position on success
return result
ensure
close
end
#returns array of strings
def readall
return [] unless open()
@fr.pos=@pos
result= []
while s=readline do
@pos=@fr.pos
result << s
end
return result
ensure
close
end
#private
def open
@fr=File.new(@rfn,'r')
rescue
nil
end
def close
@fr.close if @fr
@fr=nil
end
def readline
result=@fr.readline
# if line is complete, return it without the terminating "\n"
return result[-1,1]=="\n" ? result.chop! : nil
rescue
nil
end
end
class Writer
def initialize(filename, new = true)
@wfn=filename
if new then
File.open(@wfn, "w"){}
else
reopen
close
end
end
def <<(string)
reopen
n=nil
if @fw then
n=@fw.write(string)
@fw.write("\n")
@fw.flush
end
return n == string.bytesize
ensure
close
end
private
def reopen
@fw=File.new(@wfn, "a")
rescue
nil
end
def close
@fw.close if @fw
@fw=nil
end
end
end