How to get the width of terminal window in Ruby

前端 未结 9 1507
你的背包
你的背包 2021-01-30 16:30

Have you ever noticed that if you run rake -T in rails the list of rake descriptions are truncated by the width of the terminal window. So there should be a way to get it in Rub

9条回答
  •  佛祖请我去吃肉
    2021-01-30 16:53

    I've found that on Ubuntu, none of the other methods specified here (ENV['COLUMNS'], tput columns or hirb) give the correct result if the terminal is resized while the Ruby application is running. This is not an issue for scripts, but it is an issue for interactive consoles, such as irb.

    The ruby-terminfo gem is the best solution I've find so far to give the correct dimensions after a resize, but it requires that you install an additional gem, and is unix-specific.

    The gem's usage is simple:

    require 'terminfo'
    p TermInfo.screen_size        # [lines, columns]
    

    TermInfo internally uses TIOCGWINSZ ioctl for the screen size.

    Alternatively, as mentioned by user83510, highline's system_extensions also works:

    require 'highline'
    HighLine::SystemExtensions.terminal_size # [columns, lines]
    

    Interally, highline uses stty size on Unix, and other implementations for ncurses and Windows.

    To listen for changes to the terminal size (instead of polling), we can trap the SIGWINCH signal:

    require 'terminfo'
    Signal.trap('SIGWINCH', proc { puts TermInfo.screen_size.inspect })
    

    This is specifically useful for applications using Readline, such as irb:

    Signal.trap('SIGWINCH', proc { Readline.set_screen_size(TermInfo.screen_size[0], TermInfo.screen_size[1]) })
    

提交回复
热议问题