How to make a ruby command line application with pager?
Asked Answered
E

2

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?

Endodontist answered 13/12, 2011 at 12:4 Comment(0)
C
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.

Cecilius answered 13/12, 2011 at 12:8 Comment(0)
H
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.

Harve answered 13/12, 2011 at 16:19 Comment(2)
This is different from what i want. I want to use pager out of system .Endodontist
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.Hoyos

© 2022 - 2024 — McMap. All rights reserved.