Thursday, August 21, 2008

Ruby-Cocoa

Make the Mac talk, just like Steve Jobs did in 1984. The Ruby interface to the Mac Cocoa UI makes it quick and easy. This code will add an icon to the system Mac's menu. The menu presents two options, 'Speak' and 'Quit'. The text passed to the NSSpeechSynthesizer.startSpeakingString method is what you hear.
require 'osx/cocoa'
include OSX

class App < NSObject
  def applicationDidFinishLaunching aNotification 
    statusbar = NSStatusBar.systemStatusBar
    item = statusbar.statusItemWithLength NSVariableStatusItemLength
    image = NSImage.alloc.initWithContentsOfFile "Swirl.tiff"
    item.setImage image
    SpeechController.alloc.init.add_menu_to item
  end
end

class SpeechController < NSObject 
  def init 
    super_init
    @synthesizer = NSSpeechSynthesizer.alloc.init
    self
  end  
  def add_menu_to container
    menu = NSMenu.alloc.init
    container.setMenu menu
    item = menu.addItemWithTitle_action_keyEquivalent "Speak", "speak", ''
    item.setTarget self
    item = menu.addItemWithTitle_action_keyEquivalent "Quit", "quit", 'q'
    item.setKeyEquivalentModifierMask NSCommandKeyMask
    item.setTarget self
    #item.setTarget NSApp
  end
  def speak sender
    @synthesizer.startSpeakingString "I have a lot to say." 
  end
  def quit sender
    @synthesizer.startSpeakingString "I have nothing more to say." 
  end
end

OSX::NSApplication.sharedApplication
NSApp.setDelegate(App.alloc.init)
OSX::NSApp.run
Ruby Cocoa podcast.

Wikipedia article on Objective-C.

Ruby-Cocoa at sourceforge project.

Ruby Cocoa Resources. Beautiful applications. Beautiful code.