5 Easy Steps To Your First RubyCocoa Application

From Wurst-Wasser.net
Jump to navigation Jump to search

{{#TwitterFBLike:right}} This is my preparation for the Cetik Event 2010. 2009 I promised to hold a lecture about creating an simple RubyCocoa application. Here goes nothing...

What you need

  • Macintosh of your choice
  • MacOS X 10.5 or 10.6 (10.4 users have to install RubyCocoa[1] themselves)
  • XCode 2.4 or higher[2]
  • some time

Creating the project

Step 01: Creating the project

  1. Click Create a new XCode project...
    RubyCocoaTutorialStep1CreatingTheProject01.png
  2. ...choose Application on the left and Cocoa Application on the right and click Choose......
    RubyCocoaTutorialStep1CreatingTheProject02.png
  3. ...choose a cosy[3] place and a name for your project, I named it Wikipedia...
    RubyCocoaTutorialStep1CreatingTheProject03.png
  4. ...this is your newly created project...
    RubyCocoaTutorialStep1CreatingTheProject04.png
  5. ...edit main.m and paste the following...
    #import <RubyCocoa/RBRuntime.h>
    int main(int argc, const char* argv[])
    {
    return RBApplicationMain("rb_main.rb", argc, argv);
    }

    RubyCocoaTutorialStep1CreatingTheProject06.png
  6. ...choose File New File......
    RubyCocoaTutorialStep1CreatingTheProject06a.png
  7. ...choose Empty File and click Next...
    RubyCocoaTutorialStep1CreatingTheProject07.png
  8. ...name it rb_main.rb and save it to your project...
    RubyCocoaTutorialStep1CreatingTheProject08.png
  9. ...now paste
    require 'osx/cocoa'
    def rb_main_init
    path = OSX::NSBundle.mainBundle.resourcePath.fileSystemRepresentation
    rbfiles = Dir.entries(path).select {|x|
    /\.rb\z/ =~ x}
    rbfiles -= [ File.basename(__FILE__) ]
    rbfiles.each do |path|
    require( File.basename(path) )
    end
    end
    if $0 == __FILE__ then
    rb_main_init
    OSX.NSApplicationMain(0, nil)
    end

    RubyCocoaTutorialStep1CreatingTheProject09.png
  10. ...add to the existing Frameworks...
    RubyCocoaTutorialStep1CreatingTheProject10.png
  11. ...the RubyCocoa.framework...
    RubyCocoaTutorialStep1CreatingTheProject11.png
  12. Done! At this time you can already run your application by pressing ⌘-R. It will show an empty window, can be quit and even has an about box. Not bad for zero programming. If you're too lazy to do the above steps, you might want to download this.

Step 02: Adding an AppController

  1. There is still the Objective-C WikipediaAppDelegate class. Let's loose the class files (WikipediaAppDelegate.h and WikiAppDelegate.m)...
    Notice that the WikipediaAppDelegate.h and WikiAppDelegate.m are gone!
  2. ...and create a new file WikipediaAppController.rb...
    WikipediaAppController.rb is new!
  3. ...which we fill with:
####################################
#
#  WikipediaAppController.rb
#
#  Created by Heiko Kretschmer on 2010.
#  Copyright (c) 2010 Heiko Kretschmer. All rights reserved.
#

####################################
# Requirements
require 'osx/cocoa'

############################################################################################################
# DEBUG Settings!				   #                                                                       #
DEBUGAPPCONTROLLER			= TRUE  # -> Set this before deployment to FALSE! <-						   #
############################################################################################################

####################################
# Class "WikipediaAppController"   # 
class WikipediaAppController < OSX::NSObject

####################################
# Includes						   #
include		OSX

####################################
# Outlets                          #
ib_outlets :window
 
####################################
# Globals                          #
$globals = Hash.new

####################################
# Methoden                         #

# AwakeFromNib
def awakeFromNib
 Say("AppCrt: Awaking from nib.")

 # Preferences lesen
 #	Say("AppCrt: Reading preferences...")
 #	preferencesRead()
	
 # Preferences in window anzeigen
 #	Say("AppCrt: Applying preferences...")
 #	preferencesApply()
end # of awakeFromNib

def applicationDidBecomeActive(aNotification)
 Say("didActivate!")
 @window.makeKeyAndOrderFront_(self)
end # didActivate

def applicationWillResignActive(aNotification)
 Say("willDeactivate!")
end # didDeactivate
	
# About Window
#def aboutApp (sender)
#    thisBundle = OSX::NSBundle.mainBundle
#	copyrightString = thisBundle.objectForInfoDictionaryKey("CFBundleGetInfoString")
#	versionString   = thisBundle.objectForInfoDictionaryKey("VersionString")
#	NSApp.orderFrontStandardAboutPanelWithOptions("Copyright" => copyrightString, "ApplicationVersion" => versionString)
#end # aboutApp 
#ib_action :aboutApp

def applicationDidFinishLaunching(notification)
 Say("Application finished launching")
end

# If sent to foreground
def sendToForeground(sender)
 Say("Application coming to front")
 OSX::NSApp.activateIgnoringOtherApps:YES # Verfahren aus Schick geklaut
end

# Will Terminate
def applicationWillTerminate (notification)
 Say("Will terminate.")
end

# Should Terminate
def applicationShouldTerminate (notification)
 Say("Should terminate.")
 #	preferencesWrite()
 return NSTerminateNow
end


###############################################################################
# Private API #################################################################
private
def Say(*args)
 if (DEBUGAPPCONTROLLER==0) then return # Debugging ist aus -> raus hier
 else
  OSX::NSLog(*args)
 end # else !debug
end # Say
 
end # AppController

Step 03: Connect the AppController

  1. Before the new AppController works, we have to fix two things in MainMenu.xib...double-click it in XCode...
  2. ...set the class of the AppController to the new WikipediaAppController (is still set to the name of the WikipediaAppDelegate Objective-C class). Click the old object (Wikipedia App Delegate) and choose the new class with the inspector:
    RubyTutorialAppControllerConnections01.png
  3. Now connect the window object to the outlet of the AppController...
    RubyTutorialAppControllerConnections02.png
  4. Test your App by pressing ⌘-R. If it does not run...well...start over ;)[4]

Step 04: Adding a WebView

  1. Since we want to see the Wikipedia in our window we should add an web view:
    Open the MainMenu.xib, choose the WebView...
    RubyAppTutorialWebView01.png
  2. ...and drag it into our window:
    RubyAppTutorialWebView02.png
  3. ...set the size settings so, that the WebView will grow and shrink with the window:
    RubyAppTutorialWebView03.png
  4. Create a new outlet[5] in WikipediaAppController.rb like this:
    ib_outlets :window, :webView
  5. ...connect the WebView to your new outlet:
    RubyAppTutorialWebView04.png

So far, so good. Unfortunately the app doesn't run:

/Users/heiko/Development/Cetik RubyCocoa Tutorial/Wikipedia/build/Debug/Wikipedia.app/Contents/Resources/rb_main.rb:18:in `NSApplicationMain': NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (WebView) (OSX::OCException)
from /Users/heiko/Development/Cetik RubyCocoa Tutorial/Wikipedia/build/Debug/Wikipedia.app/Contents/Resources/rb_main.rb:18

We forgot to add the WebKit framework![6]
So, we add the framework by dragging the WebKit.framework from here...
RubyAppTutorialWebView10.png
...to here:
RubyAppTutorialWebView11.png

Now we check again if the app runs[7]. Does look exactly as before - so what was the WebView for?

Step 05: Use the WebView!

Now it's time to take a look at cocoa, the API we are going to use. The API is fairly easy to search, start here:
RubyCocoaTutorialAPIHelp01.png
For example, search for NSWebView the class we need to tell to load the http://www.wikipedia.org URL:
RubyCocoaTutorialAPIHelp02.png
Take your time to check the help, it contains everything you will ever need to develop applications.

Now let's set the URL the WebView should use by adding this line to the awakeFromNib: method:

# Setting the URL to load
@webView.setMainFrameURL_("http://www.wikipedia.org")

After hitting ⌘-R you will probably see something like this:

RubyCocoaTutorialWebViewWikipediaWindow.png

Congratulations - You made it![8]

Finetuning

There is some of finetuning that you might want to consider:


  1. I'd recommend you take a look at RubyCocoa for risks and side-effects
  2. I used XCode 3.2.1 on Mac OS X 10.6 to create this tutorial
  3. As you might have guessed, I prefer british english :-)
  4. You might also try using this Media:RubyCocoaAppTutorialAfterStep03AppController.zip
  5. As you might have guessed, an outlet is a way of connecting source and interface. You can access any object of the interface using an outlet
  6. You might have heard the sound of a hand slapping on the forehead
  7. If not, try again or use Media:RubyCocoaTutorialAfterStep04.zip
  8. In case you didn't, you might want to download the complete tutorial here: Media:RubyCocoaTutorialAfterStep05.zip