Ruby, an AppleScript Alternative – Part 1
AppleScript is a scripting language that provides the ability to control “scriptable” applications on a Mac. AppleScript provides an interface to the Apple Event messaging architecture, the means by which applications communicate with one another as well as the underlying OS.
Here is the description of AppleScript from the Apple website:
AppleScript is an English-like language used to create script files that control the actions of the computer and the applications that run on it. Much more than just a macro-language, which simply repeats your recorded actions, AppleScript scripts can “think.”
If you come from a programming background, it may take some time to get used to the “English-like” interface. Now this is not necessarily a bad thing as it makes AppleScript more approachable for those without any experience writing code.
In my search for an alternative to AppleScript, I came upon rb-appscript. Ruby appscript is an Apple event bridge that provides a framework for querying and controlling scriptable applications from Ruby. I first read about rb-appscript in this article at O’Reilly, which provides an excellent introduction to the topic.
Let’s walk through how to install rb-appscript and wrap up with a short Ruby script to verify everything is working. For installation, there are two options – one is via RubyGems, the second is to build from source. I generally build from source as I have more control over the process. The steps for doing so are shown below (you’ll find the same basic steps listed in the O’Reilly article mentioned above):
- Download rb-appscript from RubyForge (I am running rb-appscript-0.5.1)
- Extract the contents of the zip file
- From the directory where the files were extracted, run these commands from a Terminal:
- Open a text file and enter the following code:
- Save the file as test.rb and from a Terminal run the script:
> ruby test.rb
> ruby extconf.rb
> sudo make install
require "appscript" include Appscript app('TextEdit').activate
This short application does nothing more then use an application object to activate TextEdit, bringing it to the foreground (starting it if necessary). If all is well, you should see TextEdit as the top most application.
In the next tip I’ll dig a little deeper into working with rb-appscript, including a look at how to access Standard Additions such as dialog boxes.