I’m not going to explain what MacRuby is but here’s a short description from the projects website:
MacRuby is a version of Ruby 1.9, ported to run directly on top of Mac OS X core technologies such as the Objective-C common runtime and garbage collector, and the CoreFoundation framework. While still a work in progress, it is the goal of MacRuby to enable the creation of full-fledged Mac OS X applications which do not sacrifice performance in order to enjoy the benefits of using Ruby.
So, to get started you obviously need to install MacRuby, but fear not, the official website provides a graphical installer so it’s just a point-n-click operation.
In order for MacRuby not to interfere with previously installed ruby versions it prefixes all command-line executables with mac* (eg, macruby, macgem, macrake and so on) so you’ll want to keep that in mind.
Hello World
MacRuby comes bundled with HotCocoa, a idiomatic ruby interface to cocoa. Using HotCocoa makes it easy to write to write cocoa apps in your favorite text-editor so you don’t have to resort to XCode and Interface Builder.
But enough talking, it’s time for the mandatory “Hello World” app
In your text-editor of choice create a file called hello_world.rb and edit it to look like this:
require "hotcocoa"
include HotCocoa
application :name => "Hello World" do |app|
window :title => "Hello World", :frame => [500, 500, 300, 100] do |win|
win << button(:title => "Click Me!").on_action { NSLog "Hello World" }
win.will_close { exit }
end
end
And that’s it, now save the file and run it from the command-line like this:
$ macruby hello_world.rb
Try clicking the button and you should see something like this in the console:
2009-07-31 23:58:11.752 macruby[28261:10b] Hello World
Well, that’s nice and all, but I want something more
Once you start building anything serious, a single file app isn’t really viable. Fortunally though, HotCocoa comes with a generator:
$ hotcocoa my_app
This will create a directory structure for you, with some rake tasks and a skeleton app. You can try it out like this:
$ cd my_app
$ macrake
Where to go from here?
Both MacRuby and HotCocoa are pretty young and so documentation is sparse, there are however a couple of really good examples under: /Developer/Examples/Ruby/MacRuby/ and /Developer/Examples/Ruby/MacRuby/HotCocoa
Tagged with HotCocoa, MacRuby. Written by: Patrik Hedman
