6

I'm making a command line tool using Ruby. It will print a lot of text on screen. Currently, I'm using shell pipeline (may_app | more) to do so. But I think it's better to has a default pager.

It's just like what you see when execute git log . One can disable pager by using git --nopager log.

I've done quite much google work and find one gem: hirb , but it seems a little overkill.

After many tries, I'm current using shell wrapper to do so:

#!/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?

qhwa
  • 73
  • 6

2 Answers2

3

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

Some people prefer less to more for example, and others have their favorite parser options set in this var.

zed_0xff
  • 32,417
  • 7
  • 53
  • 72
3

You can use the pipe in Ruby via a call to system and provide the options (along with a nice help interface) like so:

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.

davetron5000
  • 24,123
  • 11
  • 70
  • 98
  • This is different from what i want. I want to use pager out of `system` . – qhwa Dec 14 '11 at 03:44
  • Not sure what this last comment means. This solution is pretty similar to the accepted one. The difference is that in one case you call ruby a bash script, and in the other you call a command from inside ruby. Depending on the context one is probably preferable but we don't have the full context. In both cases you get a runnable command which is able to pipe through a pager of choice or no pager at all. – Mig May 19 '22 at 06:42