Using AppleScript to Get User Input
Problem
On Mac OS X, AppleScript makes it easy to add simple graphical interface elements to programs. You want to use AppleScript from a Ruby program.
Solution
Use the AppleScript library, written by John Butler and available as the applescript gem. It lets you talk to AppleScript from Ruby.
Heres a script that uses the AppleScript class to get input through AppleScript. It also shows off the AppleScript.say method, which uses Mac OS Xs text-to-speech capabilities:
require ubygems require applescript name = AppleScript.gets("Whats your name?") AppleScript.puts("Thank you!") choice = AppleScript.choose("So which of these is your name?", ["Leonard", "Mike", "Lucas", name]) if name == choice AppleScript.say "You are right!" picture = AppleScript.choose_file("Find a picture of yourself") if File.exists?(picture) AppleScript.say "Thanks, I will now post it on Flickr for you." # Exercise for the reader: upload the file to Flickr end else AppleScript.say "But you just said your name was #{name}!" end
Discussion
The AppleScript library is just a simple wrapper around the osascript command-line interface to AppleScript. If you already know AppleScript, you can execute raw AppleScript code with AppleScript.execute:
script = ell application "Finder" to display dialog "Hello World!" + uttons {"OK"} AppleScript.execute(script)
See Also
- The manpage for osascript, available online at http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/osascript.1.html
Категории