Menus

speaking-statusbar.rb

#!/usr/bin/env macruby
framework 'cocoa'

class App
  def applicationDidFinishLaunching(aNotification)
    statusbar = NSStatusBar.systemStatusBar
    @status_item = statusbar.statusItemWithLength(NSVariableStatusItemLength)

    image = NSImage.new.initWithContentsOfFile("stretch.tiff")
    raise "Icon file 'stretch.tiff' is missing." unless image

    @status_item.setImage(image)

    SpeechController.new.add_menu_to(@status_item)
  end
end

class SpeechController
  def init
    return unless super
    @synthesizer = NSSpeechSynthesizer.new
    self
  end

  def add_menu_to(container)
    menu = NSMenu.new
    container.setMenu(menu)

    menu_item = menu.addItemWithTitle("Speak", action:"speak:", keyEquivalent:'')
    menu_item.setTarget(self)

    menu_item = menu.addItemWithTitle("Quit", action:"terminate:", keyEquivalent:'q')
    menu_item.setKeyEquivalentModifierMask(NSCommandKeyMask)
    menu_item.setTarget(NSApp)
  end

  def speak(sender)
    @synthesizer.startSpeakingString("I have nothing to say")
  end
end

NSApplication.sharedApplication
NSApp.delegate = App.new
NSApp.run

Notes:

  • 14, 26: Again, we can use “new” instead of “alloc.init”
  • 20: In Macruby, we can just call super as we would in ordinary ruby.
  • 22: just as in Rubycocoa, the init method must return self
  • 29, 32: this is our first look at the Macruby syntax for named arguments. Whereas in Rubycocoa, Objective C named arguments were added to the method name, Macruby uses Ruby 1.9’s new literal hash syntax. By collecting all arguments except the first into a hash, Macruby calls to multi-argument Objective C methods can read very naturally. So an Objective C signature like
    [menuItem addItemWithTitle: a_title action:an_action keyEquivalent:a_key]

    becomes

    menuItem.addItemWithTitle( a_title action:an_action keyEquivalent:a_key )

    (note, whitespace after the colons is optional, I omit it because I find it easier to read that way since the hash literal keys are syntax-colored in my editor)

Pages: 1 2 3