Automation with Ruby

KosmicTask Help

Automation with Ruby

Automation with Ruby

OS X automation is achieved by sending AppleEvents to an application. A combination of technologies now makes application automation possible from a wide range of scripting languages. Ruby Cocoa tasks make use of the RubyCocoa framework.

Ruby is a modern object orientated language that can also be used to power automation tasks. The KosmicTask Resource Browser contains a Ruby template, the File template, that demonstrates the basics of returning a file from a Ruby Task. Another Ruby template, the Automate app with Scripting Bridge template, demonstrates how to connect to an application in order to automate it. By combining these two templates we can quickly replicate our AppleScript powered Pages task as a Ruby powered task.

require 'osx/cocoa'
include OSX
OSX.require_framework 'ScriptingBridge'

# get application reference - see the Ruby Usage document for more info
app = OSX::SBApplication.applicationWithBundleIdentifier_("com.apple.iWork.pages")
pagesDocFilePath = ARGV[0]
rtfDocFilePath = pagesDocFilePath + ".rtf"

# open pages
myDoc = app.open_(pagesDocFilePath)

# save document
myDoc.saveAs_in_("SLDocumentTypeRichText", rtfDocFilePath)

# close document
myDoc.closeSaving_savingIn(false, nil)

# define our result file
resultFile = "result.html"

# convert our file
system "textutil -convert html -output \"#{resultFile}\" \"#{rtfDocFilePath}\""

# return our result file
puts "---"
puts "{kosmicFile: #{resultFile}, kosmicInfo: file returned}"

There are quite a few details here that are worth noting.

  • First we require the Cocoa, OS X and ScriptingBridge components to be loaded. This is essential.
  • Secondly we connect to the application we wish to automate by using its bundle identifier, which is written in reverse-DNS notation (aka a back to front URL). 
  • Thirdly we communicate with our target application using standard Ruby syntax to call the required methods. The method names used are obviously derived from their AppleScript equivalents.

Apart from that its easy to see the correspondence between the AppleScript version and the Ruby implementation.