Skip to content

Commit e4f3a2a

Browse files
committed
Implement chomp: option for gets, readline, readlines, each_line
It was added to IO methods in Ruby 2.4, but OpenSSL sockets don't have them, so any code accepting SSL sockets can't make use of it. Ref: ruby/ruby@a2144bd
1 parent d9111c2 commit e4f3a2a

File tree

2 files changed

+45
-8
lines changed

2 files changed

+45
-8
lines changed

Diff for: lib/openssl/buffering.rb

+10-8
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def read_nonblock(maxlen, buf=nil, exception: true)
232232
#
233233
# Unlike IO#gets the separator must be provided if a limit is provided.
234234

235-
def gets(eol=$/, limit=nil)
235+
def gets(eol=$/, limit=nil, chomp: false)
236236
idx = @rbuffer.index(eol)
237237
until @eof
238238
break if idx
@@ -247,7 +247,9 @@ def gets(eol=$/, limit=nil)
247247
if size && limit && limit >= 0
248248
size = [size, limit].min
249249
end
250-
consume_rbuff(size)
250+
str = consume_rbuff(size)
251+
str.chomp!(eol) if chomp && str
252+
str
251253
end
252254

253255
##
@@ -256,8 +258,8 @@ def gets(eol=$/, limit=nil)
256258
#
257259
# See also #gets
258260

259-
def each(eol=$/)
260-
while line = self.gets(eol)
261+
def each(eol=$/, chomp: false)
262+
while line = self.gets(eol, chomp: chomp)
261263
yield line
262264
end
263265
end
@@ -268,9 +270,9 @@ def each(eol=$/)
268270
#
269271
# See also #gets
270272

271-
def readlines(eol=$/)
273+
def readlines(eol=$/, chomp: false)
272274
ary = []
273-
while line = self.gets(eol)
275+
while line = self.gets(eol, chomp: chomp)
274276
ary << line
275277
end
276278
ary
@@ -281,9 +283,9 @@ def readlines(eol=$/)
281283
#
282284
# Raises EOFError if at end of file.
283285

284-
def readline(eol=$/)
286+
def readline(eol=$/, chomp: false)
285287
raise EOFError if eof?
286-
gets(eol)
288+
gets(eol, chomp: chomp)
287289
end
288290

289291
##

Diff for: test/openssl/test_pair.rb

+35
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,41 @@ def test_gets
115115
}
116116
end
117117

118+
def test_gets_chomp
119+
ssl_pair {|s1, s2|
120+
s1 << "abcd\r\n" * 50
121+
s1.close
122+
123+
50.times do
124+
assert_equal "abcd", s2.gets(chomp: true)
125+
end
126+
}
127+
end
128+
129+
def test_gets_chomp_rs
130+
rs = ":"
131+
ssl_pair {|s1, s2|
132+
s1 << "aaa:bbb"
133+
s1.close
134+
135+
assert_equal "aaa", s2.gets(rs, chomp: true)
136+
assert_equal "bbb", s2.gets(rs, chomp: true)
137+
assert_nil s2.gets(rs, chomp: true)
138+
}
139+
end
140+
141+
def test_gets_chomp_default_rs
142+
ssl_pair {|s1, s2|
143+
s1 << "aaa\r\nbbb\nccc"
144+
s1.close
145+
146+
assert_equal "aaa", s2.gets(chomp: true)
147+
assert_equal "bbb", s2.gets(chomp: true)
148+
assert_equal "ccc", s2.gets(chomp: true)
149+
assert_nil s2.gets
150+
}
151+
end
152+
118153
def test_gets_eof_limit
119154
ssl_pair {|s1, s2|
120155
s1.write("hello")

0 commit comments

Comments
 (0)