Report abuse

# ~/.autotest
module Autotest::Notification
  FAIL    = -1
  PENDING = 0
  SUCCESS = 1

  EXPIRATION_IN_SECONDS = 3

  FAIL_IMAGE    = "~/Imagens/rails_fail.png"
  SUCCESS_IMAGE = "~/Imagens/rails_success.png"

  Autotest.add_hook :ran_command do |at|
    result = at.results.last
    if result

      # Unit::Test
      tests      = result =~ /(\d+) test/ ? $1.to_i : 0
      assertions = result =~ /(\d+) assertion/ ? $1.to_i : 0
      errors     = result =~ /(\d+) error/ ? $1.to_i : 0

      # RSpec
      examples   = result =~ /(\d+) example/ ? $1.to_i : 0
      pendings   = result =~ /(\d+) pending/ ? $1.to_i : 0

      # Shared
      failures   = result =~ /(\d+) failure/ ? $1.to_i : 0

      code = 32
      msg = if result =~ /test/
        code = 31 if failures > 0 || errors > 0
        "#{pluralize('test', tests)}, #{pluralize('assertion', assertions)}, #{pluralize('failure', failures)}, #{pluralize('error', errors)}"
      else
        code = (failures > 0) ? 31 : (pendings > 0) ? 33 : 32
        "#{pluralize('example', examples)}, #{pluralize('failure', failures)}, #{pendings} pending"
      end

      if failures > 0 || errors > 0
        notify "FAIL", msg, FAIL_IMAGE, 2
      else
        notify "Pass", msg, SUCCESS_IMAGE
      end

      puts "\e[#{code}m#{'=' * 80}\e[0m\n\n"
    end
  end

  class << self
    def notify(p_title, p_msg, p_img = SUCCESS_IMAGE, p_pri = 0)
      if RUBY_PLATFORM =~ /linux/
        notify_send(p_title, p_msg, p_img)
      elsif RUBY_PLATFORM =~ /darwin/
        growl(p_title, p_msg, p_img, p_pri)
      end
    end

    def pluralize(text, number)
      "#{number} #{text}#{'s' if number != 1}"
    end

    def growl(title, msg, img, pri)
      system "growlnotify -n autotest --image #{img} -p #{pri} -m #{msg.inspect} #{title}"
    end

    def notify_send(title, msg, img)
      options = "-t #{EXPIRATION_IN_SECONDS * 1000} -i #{img}"
      system "notify-send #{options} '#{title}' '#{msg}'"
    end
  end
end