Ruby Appscript – Sweet automation

Yesterday a coworker pointed me to ruby’s appscript. I have found it nothing short of amazing.

I love my Mac, and many of us like the idea of automating our software, until we try to use AppleScript to do it. To say that Applescript is professional developer unfriendly is an understatement. I like ruby but to make ruby and applescript talk requires sending strings to osascript in just the right way and getting the output from osascript back. Not a lot of fun at all.

Enter appscript. Appscript is a ruby library that interfaces with applescript seamlessly.

What’s pretty amazing is its power after you spend a little while on the irb console and keep using the tab key for autocompletion. It even introspects the dictionary to see what is available at this time. It doesn’t always give the right thing but by trying things out and with a bit of logic you always get there.

There’s also an app called ASDictionary that will spit out the dictionary with ruby syntax, though I never found the dictionary all that useful anyway (I mean yes, it has definitions for everything, but it seldom provides info on exactly how everything is tied together or examples of use). I personally prefer trying things out on the console.

Here are a few examples of its use. You can do all this on irb immediately after installing it with sudo gem install appscript:

Driving iCal

This will get all your calendars and print their names:

require 'appscript'
app = Appscript.app("iCal")
app.calendars.get.each { |cal| puts cal.name.get }

Just expanding on this concept a little more, you can also grab all the to-dos:

app.calendars.get.each { |cal|
  cal.get.todos.get.each {|todo|
    puts todo.summary.get
  }
}

Automating Safari. Ruby to Applescript to Javascript

Haven’t tried marshaling values back as I’m just exploring, but I don’t see why it couldn’t.

require 'appscript'
app = Appscript.app("iCal")
app.open_location("http://www.google.com")
window = app.documents.get[0]
window.do_JavaScript("window.alert('Your title is '+document.title)")

I’m sure you can find some use for this. I already did – I wrote myself a quick cron to add all the JIRA tasks assigned to me to Omnifocus if I don’t already have them there. I’m looking forward to seeing what else I can put this to use.

2 thoughts on “Ruby Appscript – Sweet automation”

  1. The weird and/or interesting thing about Apple event IPC is that it’s based on RPC+queries rather than OOP, allowing your first two examples to be condensed down to this:


    require 'appscript'
    app = Appscript.app("iCal")

    puts app.calendars.name.get

    puts app.calendars.todos.summary.get

    Doesn’t always work in practice (some apps are better at it than others), but pretty neat when it does.

Comments are closed.