- Create a "Ruby-Cocoa Application" from the "New Project" dialog in XCode
- Add a "Ruby NSObject subclass" to the project called "ITunesController"
- Add an ib_outlet for a text field and an ib_action called "show_version" to the ITunesController ruby class.
- Generate an Objective-C header file that scripting bridge can use to communicate with iTunes. Use the two terminal command, sdef and sdp, within your project folder like this: "sdef /Applications/iTunes.app | sdp -fh --basename iTunes"
- Add the header file to your project.
- Add "ScriptingBridge.framework" to your project.
- Open "MainMenu.nib" in Interface Builder and add a button and a label to the Window. Also instantiate an NSObject subclass.
- Set the NSObject's class to "ITunesController". (You may need to select the "Read Class Files..." menu item to get ITunesController to show up as a valid option)
- Wire the button to your controller's "show_version" method and wire the controller's text_field outlet to the label.
Here's what my project looks like:
Here's what my Ruby "ITunesController" class looks like:
require 'osx/cocoa'
include OSX
class ITunesController < NSObject
ib_outlet :text_field
def show_version(sender)
iTunes = SBApplication.applicationWithBundleIdentifier:'com.apple.iTunes'
@text_field.setStringValue("iTunes version: #{iTunes.version}")
end
ib_action :show_version
end
Here's what the app looks like:
Now you should be able to run the project and get the iTunes version number displayed in your own application. Yeah, the end result is kind of lame but the journey was pretty cool. The interesting bits for me were:
- My Ruby class extends Cocoa's NSObject class.
- The class methods ib_outlet and ib_action are parts of the Ruby DSL for doing Cocoa development with Ruby.
- The RubyCocoa framework makes it really simple to swap out Objective-C for Ruby when doing Cocoa development.
- Everything else is the same. I still use XCode for my controllers and model and still use Interface Builder to graphically build my GUI and bind it to my code. The only difference is that I get to use Ruby and all of its beauty to get the job done.
- The downside is that I don't get anything too useful in the way of code completion while in XCode. Still might be worth it if you really dig Ruby.
3 comments:
Nice tutorial but I'd have preferred a more step-by-step like approach with lots of screenshots/code listings and/or a screencast.
Thanks for the tutorial,
Lucas
Steps 4 and 5 are not necessary. There is no need to generate the header file and add it to the project because you access the framework from Ruby.
Nice tutorial though :-)
Thanks for the clarification. I should have realized that myself... :-)
Post a Comment