Ruby - 以彩色输出打印

5
我有一个Ruby脚本(Guardfile),它执行一个rake命令。
guard :shell do

  watch(%r{^manifests\/.+\.pp$}) do |m|
    spec = `rake spec`
    retval = $?.to_i
    case retval
    when 0
       if spec.length > 0 then
          puts spec
          n "#{m[0]} Tests Failed!", 'Rake Spec', :pending         
       else
          puts spec
          n "#{m[0]} Tests Passed!", 'Rake Spec', :pending

       end
    end
end

当我在命令行上运行 'rake spec' 时,输出会带有颜色。如何让 Ruby 脚本的输出也带有颜色呢?
从命令行开始:

enter image description here

来自 Ruby 脚本:

enter image description here

更新

我能够通过使用 script 来部分解决这个问题。

在管道传输时保留bash命令的颜色

spec = `script -q /dev/null rake spec`

这种方法仍有不足之处,无法实时滚动文本。虽然它保留了颜色,但直到最后才输出任何内容。

是否有更原生的方法可以实现滚动?


尝试使用 spec = \rake spec --color``。 - Undo
好主意,我遇到了这个错误:无效选项:--color - spuder
创建一个名为“.rspec”的文件,并将其内容设置为“--color”,这样可以生效吗? - Jay Mitchell
2个回答

2
首先,rake spec --color 是无法正常工作的,因为你把 --color 传递给了 rake,而不是 rspec
Jay Mitchell 建议的颜色设置应该会起作用——在你的.rspec文件中加入以下内容:
--color

关于“实时”输出,guard-shell有一个eager命令来实现:https://github.com/guard/guard-shell/blob/master/lib/guard/shell.rb#L37-L51。不幸的是,guard-shell有两个重要的缺点:一是它不能提供退出代码的访问;二是它不能正确报告Guard中的失败(这会导致运行其他任务)。因此,对于我们在这里的需求,Guard::Shell的eager方法是无用的。相反,以下方法应该可行:
# a version of Guard::Shell's 'eager()' which returns the result
class InPty
  require 'pty'

  def self.run(command)
    PTY.spawn(command) do |r, w, pid|
      begin
        $stdout.puts
        r.each {|line| $stdout.print line }
      rescue Errno::EIO
      end
      Process.wait(pid)
    end

    $?.success?
  rescue PTY::ChildExited
  end
end

# A hack so that Guard::Shell properly throws :task_has_failed
class ProperGuardPluginFailure
  def to_s
    throw :task_has_failed
  end
end

guard :shell, any_return: true do
  watch(%r{^manifests\/.+\.pp$}) do |m|
    ok = InPty.run('rake spec')
    status, type = ok ? ['Passed', :success] : ['Failed', :failed]
    n "#{m[0]} Tests #{status}!", 'Rake Spec', type
    ok ? nil : ProperGuardPluginFailure.new
  end
end

上面的内容对于一个新的守卫插件来说看起来很理想 - 是个好主意吗?

-1

我不熟悉Guardfiles。你能用gems吗?colorize gem非常好用。

https://github.com/fazibear/colorize

安装它:

$ sudo gem install colorize

使用它:

require 'colorize'

puts "Tests failed!".red
puts "Tests passed!".green

1
没有回答楼主的问题,但是它让我找到了 colorize gem,这正是我想要的。 :) - Joshua Pinter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接