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


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net