【问题标题】:How to make a ruby command line application with pager?如何使用寻呼机制作 ruby​​ 命令行应用程序?
【发布时间】:2012-01-19 07:25:10
【问题描述】:

我正在使用 Ruby 制作命令行工具。它会在屏幕上打印很多文本。目前,我正在使用 shell 管道 (may_app | more) 来执行此操作。但我认为最好有一个默认寻呼机。

就像你在执行 git log 时看到的一样。可以使用git --nopager log 禁用寻呼机。

我在谷歌上做了很多工作,找到了一颗宝石:hirb,但这似乎有点矫枉过正。

经过多次尝试,我目前正在使用 shell 包装器:

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

它有效。但是有没有更好的方法?

【问题讨论】:

    标签: ruby command-line pager


    【解决方案1】:

    您可以通过调用 system 在 Ruby 中使用管道,并提供如下选项(以及漂亮的帮助界面):

    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
    

    现在,您在命令行上支持--pager--no-pager,这很好。

    【讨论】:

    • 这与我想要的不同。我想使用system 之外的寻呼机。
    【解决方案2】:

    你做得对。但如果使用more,您最好从$PAGER 环境变量中获取寻呼机,如果有的话。

    例如,有些人更喜欢less 而不是more,而其他人则在此变量中设置了他们最喜欢的解析器选项。

    【讨论】:

      猜你喜欢
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多