How to bridge Ruby and AppleScript

How to bridge Ruby and AppleScript

Not that long ago I gave a demo in which I showed how it was possible to control iTunes from my laptop using native Ruby code.

This was all possible because of a great little gem called rb-appscript.

rb-appscript is a really neat Ruby to AppleScript bridge that gives you the power to effortlessly control any AppleScript aware applications from within your very own Ruby applications.

Launching iTunes and the DVD Player via irb

Assuming you have already installed the rb-appscript gem open up a Terminal shell and lauch irb. What we are going to do is in a few lines of code open up iTunes from ruby.
>> require 'appscript'
=> true (notice above we don't need to prefix the gem with rb-)
>> it = Appscript.app('iTunes')
>> it.run

Now how easy was that! iTunes just started up as soon as we ran it.run. Obviously if you already had iTunes running you would be disappointed because nothing would have happened.
You can use the above code for any application you could easily have just done
>> Appscript.app('Dvd Player').run
If you wanted to launch the dvd player.

Let’s tell iTunes what track we want to play

In the following example I am going to show you how you can retrieve a list of tracks from your Music library and tell iTunes to play our selection.
>> require 'appscript'
=> true (notice above we dont need to prefix the gem with rb-)
>> it = Appscript.app('iTunes')
>> it.run

Print out our tracks we have available to us
>> track_count = 0
>> it.playlists["Music"].tracks.get.each do | track |
?> puts "#{track_count += 1}. #{track.artist.get} - #{track.name.get}"
>> end

Ok play the 3rd track
t.playlists["Music"].tracks[3].play
Magic happens the song starts playing!

Script Editor + ASTranslate is your friend

Now the examples I have given you are very basic however if you want to do more then you should launch Script Editor and load the application dictionary that gives you access to all commands and properties you can change for that application.

ASTranslate is a great developer tool that allows you to write normal AppleScript commands and it will attempt to translate this into the rb-appscript equivalent!  So if you come across any cool AppleScripts out there you may be lucky and be able to translate them into ruby code!

I was amazed at how easy it was for me to command iTunes to do what I wanted it to do all from within my ruby application.

Useful references

http://appscript.sourceforge.net
http://www.apeth.com/rbappscript/10examples.html

No Comments

Leave a Reply