How to make ruby โ€‹โ€‹command line application with pager?

I am making a command line tool using Ruby. It will print a lot of text on the screen. I am currently using a shell pipeline ( may_app | more ) for this. But I think it's better to have a default pager.

This is just what you see when doing git log . You can disable the pager using git --nopager log .

I did a lot of work on Google and found one stone: hirb , but that seems a bit crowded.

After many attempts, I use a shell wrapper for this:

 #!/bin/bash # xray.rb is the core script # doing the main logic and will # output many rows of text on # screen XRAY=$HOME/fdev-xray/xray.rb if [ "--nopager" == "$1" ]; then shift $XRAY $* else $XRAY $* | more fi 

It works. But is there a better way?

+6
source share
2 answers

You are doing it right. But instead, using more , you'd better get a pager from the $PAGER environment variable, if any.

Some prefer, for example, less - more , while others have their favorite parser options set in this var.

+3
source

You can use the channel in Ruby by calling system and provide parameters (along with a convenient help interface) as follows:

 require 'optparse' pager = ENV['PAGER'] || 'more' option_parser = OptionParser.new do |opts| opts.on("--[no-]pager", "[don't] page output using #{pager} (default on)") do |use_pager| pager = nil unless use_pager end end option_parser.parse! command = "cat #{ARGV[0]}" command += " | #{pager}" unless pager.nil? unless system(command) STDERR.puts "Problem running #{command}" exit 1 end 

Now you support --pager and --no-pager on the command line, which is nice to do.

+2
source

Source: https://habr.com/ru/post/903678/


All Articles