Skip to content

Instantly share code, notes, and snippets.

@mizoR
Created June 21, 2014 10:21
Show Gist options
  • Save mizoR/8780da6d05a15da58e7a to your computer and use it in GitHub Desktop.
Save mizoR/8780da6d05a15da58e7a to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'open3'
require 'optparse'
module RunAndNotify
def self.parse!(argv)
notifiers = []
opt = OptionParser.new
opt.on('--notifier NOTIFIER') {|v|
notifiers << RunAndNotify.const_get("#{v}Notifier")
}
opt.parse!
opt.permute! argv
command = ARGV.join(' ')
self.new(command, notifiers: notifiers.map {|c| c.new})
end
def self.new(*argv)
Runner.new(*argv)
end
class Result
attr_reader :command, :out, :err, :status
def initialize(command, out, err, status)
@command = command
@out = out
@err = err
@status = status
end
def render
<<-EOM.gsub(/^ {8}/, '')
****** COMMAND ******
#{self.command}
****** STATUS ******
#{self.status.inspect}
****** STDOUT ******
#{self.out}
****** STDERR ******
#{self.err}
EOM
end
end
class Runner
attr_accessor :notifiers
def initialize(command, options={})
@command = command
@notifiers = options[:notifiers] || []
end
def run_and_notify
result = self.run
self.notifiers.each do |notifier|
notifier.notify(result)
end
result.status
end
def run
_ = Open3.capture3(@command)
Result.new(@command, *_)
end
end
module Notifier
class Base
def notify(_)
raise NotImplementedError
end
end
end
class StdoutNotifier
def notify(result)
puts result.render
end
end
end
if __FILE__ == $0
runner = RunAndNotify.parse!(ARGV)
status = runner.run_and_notify
exit status.exitstatus
end
__END__
=head1 NAME
run_and_notify - run a cron job and notify result to what you want.
=head1 USAGE
0 9 * * * /path/to/run_and_notify --notifier Stdout -- "echo 'Good morning!'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment