lib/polyphony/extensions/io.rb in polyphony-0.19 vs lib/polyphony/extensions/io.rb in polyphony-0.20

- old
+ new

@@ -1,7 +1,10 @@ # frozen_string_literal: true +require 'open3' + +# IO overrides class ::IO class << self alias_method :orig_binread, :binread def binread(name, length = nil, offset = nil) File.open(name, 'rb:ASCII-8BIT') do |f| @@ -16,33 +19,38 @@ f.seek(offset) if offset f.write(string) end end - EMPTY_HASH = {} + EMPTY_HASH = {}.freeze alias_method :orig_foreach, :foreach def foreach(name, sep = $/, limit = nil, getline_args = EMPTY_HASH, &block) - sep, limit = $/, sep if sep.is_a?(Integer) + if sep.is_a?(Integer) + sep = $/ + limit = sep + end File.open(name, 'r') do |f| f.each_line(sep, limit, getline_args, &block) end end alias_method :orig_read, :read def read(name, length = nil, offset = nil, opt = EMPTY_HASH) - opt, length = length, nil if length.is_a?(Hash) + if length.is_a?(Hash) + opt = length + length = nil + end File.open(name, opt[:mode] || 'r') do |f| f.seek(offset) if offset length ? f.read(length) : f.read end end # alias_method :orig_readlines, :readlines # def readlines(name, sep = $/, limit = nil, getline_args = EMPTY_HASH) # File.open(name, 'r') do |f| - # puts "readlines(#{sep.inspect}, #{limit.inspect}, #{getline_args.inspect}" # f.readlines(sep, limit, getline_args) # end # end alias_method :orig_write, :write @@ -52,14 +60,14 @@ f.write(string) end end alias_method :orig_popen, :popen - def popen(*args) - Open3.popen2(*args) do |i, o, t| - yield o - end + def popen(cmd, mode = 'r') + return orig_popen(cmd, mode) unless block_given? + + Open3.popen2(cmd) { |_i, o, _t| yield o } end end # def each(sep = $/, limit = nil, chomp: nil) # sep, limit = $/, sep if sep.is_a?(Integer) @@ -80,26 +88,30 @@ # def getc # end alias_method :orig_gets, :gets - def gets(sep = $/, limit = nil, chomp: nil) - sep, limit = $/, sep if sep.is_a?(Integer) + def gets(sep = $/, _limit = nil, _chomp: nil) + if sep.is_a?(Integer) + sep = $/ + _limit = sep + end sep_size = sep.bytesize @gets_buffer ||= +'' loop do idx = @gets_buffer.index(sep) return @gets_buffer.slice!(0, idx + sep_size) if idx - data = readpartial(8192) - if data + if (data = readpartial(8192)) @gets_buffer << data else return nil if @gets_buffer.empty? - line, @gets_buffer = @gets_buffer.freeze, +'' + + line = @gets_buffer.freeze + @gets_buffer = +'' return line end end # orig_gets(sep, limit, chomp: chomp) end @@ -128,10 +140,11 @@ str << a str << "\n" unless a =~ /\n$/ end end write s + nil end # def readbyte # end @@ -142,16 +155,15 @@ # end # def readlines(sep = $/, limit = nil, chomp: nil) # end - def write_nonblock(string, options = {}) + def write_nonblock(string, _options = {}) # STDOUT << '>' write(string, 0) end - def read_nonblock(maxlen, buf = nil, options = nil) + def read_nonblock(maxlen, buf = nil, _options = nil) # STDOUT << '<' buf ? readpartial(maxlen, buf) : readpartial(maxlen) end - end