Kernel#at_exit()
を知ったのでメモ。
sensu-pluginでプラグインを書くと以下のような実行ファイルを作ることになる。
my_check.rb
#!/usr/bin/env ruby
require 'sensu-plugin/check/cli'
class MyCheck < Sensu::Plugin::Check::CLI
check_name 'my_awesome_check' # defaults to class name
option :foo, :short => '-f' # Mixlib::CLI is included
def run
ok "All is well"
end
end
こうやって実行する
$ ruby ./my_check.rb
All is well
さてここで感じる違和感。my_check.rbではMyCheckクラスを定義しただけで#run
メソッド呼び出す記述してないのに実行されてる、なんで!?
答え: Kernel#at_exit()
。プログラムexit時に実行されるcallbackを登録できる。このcallback内でMyCheck.new.runしてました。 https://github.com/sensu-plugins/sensu-plugin/blob/master/lib/sensu-plugin/cli.rb#L53-L68