Skip to content

Commit 1c763ef

Browse files
committed
Add limit argument to gets method
Ruby's IO class defines the #gets method as having an optional limit argument. This can either be passed in as an integer for the first argument or passed in addition to the delimiter. This makes argument handling a little awkward unfortunately.
1 parent 640b73c commit 1c763ef

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

lib/net/sftp/operations/file.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,15 @@ def read(n=nil)
8282
# returns the bytes read (including +sep_string+). If +sep_string+ is
8383
# omitted, it defaults to +$/+. If EOF is encountered before any data
8484
# could be read, #gets will return +nil+.
85-
def gets(sep_string=$/)
85+
def gets(sep_or_limit=$/, limit=Float::INFINITY)
86+
if sep_or_limit.is_a? Integer
87+
sep_string = $/
88+
lim = sep_or_limit
89+
else
90+
sep_string = sep_or_limit
91+
lim = limit
92+
end
93+
8694
delim = if sep_string.length == 0
8795
"#{$/}#{$/}"
8896
else
@@ -92,7 +100,7 @@ def gets(sep_string=$/)
92100
loop do
93101
at = @buffer.index(delim)
94102
if at
95-
offset = at + delim.length
103+
offset = [at + delim.length, lim].min
96104
@pos += offset
97105
line, @buffer = @buffer[0,offset], @buffer[offset..-1]
98106
return line

test/test_file.rb

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,21 @@ def test_gets_when_no_such_delimiter_exists_in_stream_should_read_to_EOF
9191
assert @file.eof?
9292
end
9393

94+
def test_gets_with_integer_argument_should_read_number_of_bytes
95+
@sftp.expects(:read!).returns("hello world\ngoodbye world\n\nfarewell!\n")
96+
assert_equal "hello w", @file.gets(7)
97+
end
98+
99+
def test_gets_with_delimiter_and_limit_should_read_to_delimiter_if_less_than_limit
100+
@sftp.expects(:read!).returns("hello world\ngoodbye world\n\nfarewell!\n")
101+
assert_equal "hello w", @file.gets("w", 11)
102+
end
103+
104+
def test_gets_with_delimiter_and_limit_should_read_to_limit_if_less_than_delimiter
105+
@sftp.expects(:read!).returns("hello world\ngoodbye world\n\nfarewell!\n")
106+
assert_equal "hello", @file.gets("w", 5)
107+
end
108+
94109
def test_gets_at_EOF_should_return_nil
95110
@sftp.expects(:read!).returns(nil)
96111
assert_nil @file.gets
@@ -156,4 +171,4 @@ def test_stat_should_return_attributes_object_for_handle
156171
@sftp.expects(:fstat!).with("handle").returns(stat)
157172
assert_equal stat, @file.stat
158173
end
159-
end
174+
end

0 commit comments

Comments
 (0)