【问题标题】:Event Handler for Guard (on exit)?Guard的事件处理程序(退出时)?
【发布时间】:2013-10-28 17:24:29
【问题描述】:

我有一个通知系统,当guard-rspec 失败时,它会亮起红色的LED,当它通过时,会亮起绿色,这一切都很好,但我正在寻找一种在我退出时关闭灯的方法(或防护崩溃)。

我想知道是否有办法捕捉 "On Exit" 事件并运行一些代码?

另外,有没有办法捕捉异常(如 'on error' 事件)?

【问题讨论】:

  • 我认为保护文件只是红宝石。您是否尝试添加 at_exit 挂钩?

标签: ruby rspec guard


【解决方案1】:

使用警卫回调

根据https://github.com/guard/guard/wiki/Create-a-guard,当Guard 退出时会调用#stop 方法。

Guard 自述文件的Callback 部分表明您可以在运行之前或之后挂钩#stop 方法。没有迹象表明如果 Guard 崩溃,此方法将运行任何东西,因此它可能仅适用于干净退出。

这是一个未经测试的示例。

# Guardfile

require 'led'

guard :rspec do
    watch('spec/*')

    callback(:stop_end) { set_led(:off) }
end

使用包装脚本

您可以创建一个 ruby​​ 脚本来运行 Guard、阻止并在 Guard 完成运行后关闭灯,即使崩溃也是如此。

#!/usr/bin/env ruby
# wrapper.rb

require 'led'

system("guard")
set_led(:off)

phoet 的 at_exit 建议

假设任何崩溃的 Guard 都不会干扰 at_exit 回调,这个方法应该和包装脚本一样工作。

# Guardfile

require 'led'

at_exit { set_led(:off) }

guard :rspec do
    watch('spec/*')
end

我通过运行 Guard 测试了这个方法,然后在一个单独的终端中......

$ pkill -15 -f guard     # same as Ctrl-c, triggers at_exit
$ pkill -9  -f guard     # kills ruby, does not trigger at_exit

【讨论】:

  • at_exit 可以工作,但是在使用 bundler 时,它有一个小问题,所以为了解决这个问题,我做了:at_exit do Bundler.with_clean_env { system "digicolor off" } end
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
相关资源
最近更新 更多