RubyCocoa Example: SpeakLine

I’m working my way through Cocoa Programming for Mac OS X by Aaron Hillegass, which would be the perfect book for what I want to learn, except it’s using Objective-C and not RubyCocoa. So I’m getting double the exercise, following along with the Obj-C examples and then translating into RubyCocoa. Today: Chapter 4. The example: a program that will speak a line the user types in.

I won’t go through the Interface Builder set-up, since it’s in the book, but the app will look like this:

SpeakLine window

If you’ve been playing around with Interface Builder, you should see from my code below what needs to be set up. (oh, and that thing in the bottom left corner is a Color Well)

Make a Cocoa-Ruby Application in XCode. Set up the nib file as it shows in the book, with one exception: don’t “Create Files for AppController” in Interface Builder, do that later by hand in XCode by adding a new “Ruby NSObject subclass” file to the project. Call it AppController.rb.

# the first line of any RubyCocoa file:
require 'osx/cocoa'

# create the class as a subclass of NSObject
class AppController < OSX::NSObject

# list the outlets that were created in Interface Builder,
# they'll be used as variables like @textField

ib_outlets :textField, :colorWell

# we're going to define an init method, but it's not
# necessary for all applications

def init
# when calling a super's method, preceed the method name by super_
super_init
# we'll throw a lot of stuff in the log for now,
# it'll show up when the program is run

OSX::NSLog("init")
# creating a new variable of type NSSpeechSynthesizer
# with the default system voice

@speechSynth = OSX::NSSpeechSynthesizer.alloc.init
# when overriding the init command, make sure to return self:
self
end

# awakeFromNib is run after everything's initialized, but
# before the user can do anything. I'm not actually sure
# why both methods are necessary...

def awakeFromNib
# setting the color shown in the Color Well to be that of
# the initial contents of textField

@colorWell.setColor(@textField.textColor)
end

# the method to speak the given text
def sayIt(sender)
OSX::NSLog("sayIt")
# get string that the user entered
string = @textField.stringValue.to_s
# if it's empty, don't do anything
return if string.length == 0
# speak the text
@speechSynth.startSpeakingString(string)
end

# stop speaking the given text
def stopIt(sender)
# here I tried puts intead of NSLog, just to see what the difference was
puts("stopIt")
# stop speaking. simple, yes?
@speechSynth.stopSpeaking
end

# change the color of the text in the textField based on
# what the user chooses from the Color Well

def changeTextColor(sender)
@textField.setTextColor(sender.color)
OSX::NSLog("changing text color")
end

end

Build. Run. Make your computer say dirty things.

Advertisements