Ruby to Growl, with callbacks

I wanted to write a script that used Growl to notify a user. That user could click on the Growl sidle-up, and that would make the script do something. It took me a while to figure out callbacks from Growl to the originating app, so I thought I’d write it down.

There are a couple of Growl libraries out there, but the code that best suited my needs comes from Satoshi Nakagawa’s LimeChat. Since it’s not packaged separately, I include it here.

A bit more detail on the proof-of-concept app. The first balloon looks like this:

Stretch1

When I click on it, the app pops up another notification and exits:

Stretch2

Here’s the code:

require osx/cocoa
include OSX
require growl

class GrowlController
  # The different kinds of messages you might send to Growl.
  PING_KIND = stretch
  ACK_KIND = ack

  # Tell the Growl Notifier class that we’ll be handling
  # callbacks from Growl.
  def initialize
    @growl = Growl::Notifier.alloc.initWithDelegate(self)
    @growl.start(:this_program, [PING_KIND, ACK_KIND])
  end

  # Send the initial message. The "context" argument 
  # tells Growl that we want a callback.
  def ping
    @growl.notify(kind = PING_KIND,
                  title = Stretch!‘,
                  description = You have thirty seconds.‘,
                  context = "new", sticky = true, priority = 0)
  end

  # This is the callback method for clicks.
  def growl_onClicked(sender, context)
    @growl.notify(kind = ACK_KIND,
                  title = Bye!‘,
                  description = Saw your click.‘,
                  context = nil, sticky = true, priority = 0)
    # I exit! instead of exit because the Cocoa framework catches
    # Ruby’s SystemExit exception.
    exit!
  end
end

if $0 == __FILE__ then
  growl_controller = GrowlController.new
  growl_controller.ping

  # Although it has no UI, this has to be an OS X application because
  # the run loop is needed to handle Growl callbacks.
  NSApplication.sharedApplication
  NSApp.run
end

One Response to “Ruby to Growl, with callbacks”

  1. Exploration Through Example » Blog Archive » Soliciting reviewers and advice-givers Says:

    […] Safari. It’ll also show you how to write code that makes use of Mac framework features (like sending Growl notifications and putting controllers for your scripts in the status bar). It won’t be your definitive […]

Leave a Reply

You must be logged in to post a comment.