1. Introduction
What is appscript?
Ruby appscript (rb-appscript) is an easy-to-use Apple event bridge that allows 'AppleScriptable' applications to be controlled by ordinary Ruby scripts. Appscript makes Ruby an excellent alternative to Apple's own AppleScript language for automating your Mac.
For example, to get the value of the first paragraph of the topmost document in TextEdit:
app('TextEdit').documents[1].paragraphs[1].get
This is equivalent to the AppleScript statement:
tell application "TextEdit"
get paragraph 1 of document 1
end tell
The following script uses appscript to create a new "Hello World!" document in TextEdit:
#!/usr/bin/env ruby
require "appscript"
include Appscript
app('TextEdit').documents.end.make(
:new => :document,
:with_properties => {:text => "Hello World!\n"}
)
Before you start...
In order to use appscript effectively, you will need to understand the differences between the Apple event and Ruby object systems.
In contrast to the familiar object-oriented approach of other inter-process communication systems such as COM and Distributed Objects, Apple event IPC is based on a combination of remote procedure calls and first-class queries - somewhat analogous to using XPath over XML-RPC.
While appscript uses an object-oriented-like syntax for conciseness and readability, like AppleScript, it behaves according to Apple event rules. As a result, Ruby users will discover that some things work differently in appscript from what they're used to. For example:
- object elements are one-indexed, not zero-indexed like Ruby arrays
- referencing a property of an application object does not automatically return the property's value (you need a
get
command for that) - many applications allow a single command to operate on multiple objects at the same time, providing significant performance benefits when manipulating large numbers of application objects.
Chapters 2 and 3 of this manual provide further information on how Apple event IPC works and a tutorial-based introduction to the Ruby appscript bridge. Chapter 4 describes various ways of getting help when scripting applications. Chapters 5 through 12 cover the appscript API, and chapter 13 discusses techniques for optimising performance.