Saturday, January 05, 2008

Mac OS X automation in ruby

Mac OS X ships with a tool called Automator, using automator you can create scripts to perform a task. Its kinda macro recording tool. Those who are most used to mac os x, can also write scripts which will perform any task they want. These scripts are called as applescript. Applescript has a friendly syntax so you don't have to be programmer to start with. More information @ Apple Scripting

But why learn one more syntax, just for the sake of using it. Yes, you can control Mac application from within in ruby. you need to install Ruby OSA - Ruby bridge to apple event manager. This enables us to call any application in mac, and control them. for example: you can Open iTunes and get current playing song and you can set that as you status message in your iChat application.

Ruby OSA, also comes with documentation tool, which creates a ruby doc, with list of available methods of a mac application. So using it you can right away know the interfaces, and methods to control any application
rdoc-osa --name <Application-Name>

ex:
rdoc-osa --name Adium

A Sample Script:

require 'rubygems'
require 'rbosa'
require 'httpclient'
require 'hpricot'


client = HTTPClient.new
uri = 'http://www.google.com/search?q=ind+vs+aus'
resp = client.get uri
doc = Hpricot.parse(resp.body.content)
msg = doc.search("//div[@id='3po']//td[2]/[1]/div")
app = OSA.app('Adium')

app.adium_controller.my_status_message = msg

The above ruby  code, retrieves latest cricket score of the match india vs australia, and set it as status message in the Adium (ver 1.1.4), chat application. Incase you are trying with different chat application/ different version of Adium you can always generate ruby docs (rdoc-osa command) and dig further.

Some tips in getting here:

1) You need to install XCode from optional installs of the Mac OS X dvd - this to get rid of the ruby gems updade error in Leopard.

2) get the required ruby library using ruby gems.

Recommended Blog Posts