Last Updated: February 25, 2016
·
246
· malikbakt

Running system commands with logging

require 'open3'

module Runnable

  class RunnableError < Exception; end

  extend ActiveSupport::Concern

  def logger
    Rails.logger
  end

  def run(command, options = {})
    message = "executing `#{command}`\n"

    stdout, stderr, status = Open3.capture3(command)

    if status.success?
      message << stdout
      logger.info message
    else
      message << stderr
      logger.error message
      raise RunnableError.new(stderr)
    end
  end

end