Mar 14 2008
Ruby, an AppleScript Alternative - Part 4
My intention in starting this series of posts on Ruby was to re-write two short AppleScript applications; one that turns down the volume at shutdown, and one that resets the volume upon bootup. We’ve covered enough information up to this point to have all we need to write the Ruby version (using rb-appscript).
The AppleScript example we are porting to Ruby is as follows:
tell application "Finder"
display dialog "What would you like to do?"
buttons {"Shutdown", "Restart", "Cancel"} default button "Cancel"
with icon caution
if button returned is "Shutdown" then
set volume 0
shut down
else if button returned is "Restart" then
set volume 0
restart
end if
end tell
Pretty simple application, display a dialog box with three options and based on the selected option, shut down the system, go to sleep or do nothing. The application to reset the volume at boot time is all of one line:
set volume 5
You can get the specifics of how I used these scripts by referring back to the original post.
The Ruby version of the first script looks as follows:
require 'osax' include OSAX # Display dialog box and get user request dialog = osax.display_dialog( "What would you like to do?", :buttons => ["Shutdown", "Restart", "Cancel "], :default_button => “Cancel “, :with_title => “System Shutdown…”, :with_icon => :caution) if dialog[:button_returned] == “Shutdown” puts “Shutdown” osax.set_volume(0) app(”System Events”).shut_down() elsif dialog[:button_returned] == “Restart” puts “Restart” osax.set_volume(0) app(”System Events”).restart() end
The Ruby code to reset the volume is as simple as its AppleScript counterpart:
require 'osax' include OSAX # Turn volume up (range is 0 to 7) osax.set_volume(5)
One caveat worth mentioning regarding the Ruby code: notice there is space in the references to “Cancel ” - You can read why that is by following this thread on the rb-appscript discussion/mailing list.
Additional Resources:
I’ll leave you with a few additional resources that should be helpful if you are new to rb-appscript and/or AppleScript:
Additional posts in the series: Part 1, Part 2, Part 3, Part 5, Part 6
Tips by RSS
Tips by Email
