Skip to content

Commit

Permalink
Move IO.console def to common code
Browse files Browse the repository at this point in the history
This should work largely the same across all backends.
  • Loading branch information
headius committed Jan 14, 2024
1 parent e04d339 commit 810eeb0
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 39 deletions.
39 changes: 39 additions & 0 deletions lib/ffi/io/console/common.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,44 @@
# Methods common to all backend impls
class IO
# TODO: Windows version uses "conin$" and "conout$" instead of /dev/tty
def self.console(sym = nil, *args)
raise TypeError, "expected Symbol, got #{sym.class}" unless sym.nil? || sym.kind_of?(Symbol)

# klass = self == IO ? File : self
if defined?(@console) # using ivar instead of hidden const as in MRI
con = @console
# MRI checks IO internals : (!RB_TYPE_P(con, T_FILE) || (!(fptr = RFILE(con)->fptr) || GetReadFD(fptr) == -1))
if !con.kind_of?(File) || (con.kind_of?(IO) && (con.closed? || !FileTest.readable?(con)))
remove_instance_variable :@console
con = nil
end
end

if sym
if sym == :close
if con
con.close
remove_instance_variable :@console if defined?(@console)
end
return nil
end
end

if !con
begin
con = File.open('/dev/tty', 'r+')
rescue
return nil
end

con.sync = true
@console = con
end

return con.send(sym, *args) if sym
return con
end

def getch(*, **opts)
raw(**opts) do
getc
Expand Down
39 changes: 0 additions & 39 deletions lib/ffi/io/console/native_console.rb
Original file line number Diff line number Diff line change
Expand Up @@ -211,43 +211,4 @@ def cursor_up(n)

self
end

# TODO: Windows version uses "conin$" and "conout$" instead of /dev/tty
def self.console(sym = nil, *args)
raise TypeError, "expected Symbol, got #{sym.class}" unless sym.nil? || sym.kind_of?(Symbol)

# klass = self == IO ? File : self
if defined?(@console) # using ivar instead of hidden const as in MRI
con = @console
# MRI checks IO internals : (!RB_TYPE_P(con, T_FILE) || (!(fptr = RFILE(con)->fptr) || GetReadFD(fptr) == -1))
if !con.kind_of?(File) || (con.kind_of?(IO) && (con.closed? || !FileTest.readable?(con)))
remove_instance_variable :@console
con = nil
end
end

if sym
if sym == :close
if con
con.close
remove_instance_variable :@console if defined?(@console)
end
return nil
end
end

if !con
begin
con = File.open('/dev/tty', 'r+')
rescue
return nil
end

con.sync = true
@console = con
end

return con.send(sym, *args) if sym
return con
end
end

0 comments on commit 810eeb0

Please sign in to comment.