Mac ruby to the max - Brendan G. Lim


Published on

My presentation will be on the topic of MacRuby. MacRuby is relevent to Ruby developers because it allows us to dive into the world of Mac OS X development using Ruby 1.9. Unlike RubyCocoa, where we would need to use both Ruby and Objective-C, MacRuby's API allows us to just use Ruby.

I will go into a brief history of MacRuby and explain just why it is important to us as Ruby developers. I will then do some live coding of a quick desktop application using MacRuby. Attendees will be able to take away from the presentation a good understanding of MacRuby and the passion to develop something of their own using it.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

  • - Objective-C is the primary language for Cocoa development. If you’ve ventured into Mac OSX, iPhone or iPad development you’ve been faced with the decision to learn Objective-C.
    - Objective-C is essentially object oriented extensions to the C language
    - It’s a strongly typed language and is influenced by Smalltalk like Ruby -- Objective-C also has Smalltalk-like messaging
    - There’s garbage collection in Objective-C 2.0 and also there’s also 32-bit and 64-bit support
  • - Cocoa is a set of object-oriented frameworks used to create Max OSX and iPhone OS applications.
    - It includes two major frameworks, Foundation and AppKit.
    - AppKit contains all the objects you need to implement your graphical user interface.
    - Foundation includes a base layer of classes that can be used for any type of Cocoa app.
    - Cocoa apps are typically developed using Xcode and Interface builder using Objective-C.
  • - Core Foundation is included in Foundation Kit and is a C API that is a mix of low-level routines and wrapper functions
    - The most important use of Core Foundation is for passing its own primitive types to numerous GUI related C routines
    - You can recognize a Core Foundation function because the naming almost always starts with CF. Some popular ones are CFRetain and CFRelease for memory management.
    - Most of Core Foundation was actually open sourced by Apple as a project called CF-Lite
  • - So what’s the big deal with Objective-C anyway?
    - Why would we want to use Ruby instead of Objective-C?
  • I’m going to go through some differences between Ruby and Objective C. In the following slides, the lines colored in red is ruby code and blue is Objective-C. Here’s one of the most basic examples I can show.

    - Here you can see how we pass a parameter to a method in ruby and in Objective-C.
    - Also, if you’re wondering what the square braces are, they are for binding a message to an object in Objective-C.
    - Not that bad but it gets more complicated.
  • - In Objective-C the colon separates names and arguments.
    - It looks like a hash, but it’s not and the order for which arguments are passed in matters.
    - Also it’s good to note that most arguments are identified by name and the first argument is usually included in or attached to the method name.
  • WIthin Objective-C this is how we would create a new array. We are allocating a NSMutableArray then we are initializing it. Here we’re starting to see how much more typing we’re going to have to do to accomplish the same thing in Objective-C.
  • - In this example you can really see how much more we have to do to just strip the white space from a string.
  • - So, above is how we would create a hash in Ruby and below is how you would have to do, the exact same thing that we can accomplish in one line, in Objective-C.
    - Wouldn’t it be great if we could use Ruby instead of doing all of this?
    - Unless you really really like typing, I don’t see how Objective-C could seem more appealing at this point.
  • - So, this brings us to, RubyCocoa.
  • - So that brings us now to RubyCocoa
    - RubyCocoa is a MacOSX framework
    - It’s a bridge between Objective-C and Ruby and it can manipulate Objective-C objects using Ruby
    - It runs on Ruby 1.8 and it allows you to simply write Cocoa apps in Ruby.
    - Also, it ships standard with OSX Leopard, so if you have Leopard or Snow Leopard on your Mac, you’ve got RubyCocoa.
  • - So, this is a comparison between RubyCocoa and Objective-C.
    - This example shows the setObject forKey function in Objective-C.
    - On top you can see the RubyCocoa implementation, which is more ruby like but we are oddly mixing camelcase with underscores.
  • - So why not RubyCocoa?
    - If we’ve already got something that allows us to use Ruby to make Cocoa applications, then why should I use MacRuby?
  • - Since RubyCocoa is a bridge between Obj-C and Ruby, that means that performance is obviously going to be sacrificed.
    - There are also two runtimes and two garbage collectors.
    - Also, there’s expensive object conversions.
    - For example, the first time you access the NSTableView class, RubyCocoa will retrieve all of the necessary info regarding this class and will create a Ruby class of the same name to act as a proxy on demand.
  • - So, this is where MacRuby comes in.
    - MacRuby is set to be the replacement for RubyCocoa.
    - So if you’re not too much of a fan of Objective-C then you’re going to like MacRuby.
  • If you aren’t much of an Objective-C fan you’re going to be really happy with MacRuby.
  • - MacRuby is Ruby 1.9 ported to run on top of Objective-C runtime. So all classes, methods, and objects are all objective-c. They accomplished this by taking advantage of CoreFoundation. This gives you things like native threads, obj-c’s garbage collector, and much more.
    - Project originally started by Laurent Sansonetti of Apple, who also helped out with RubyCocoa
    - Unlike RubyCocoa, there’s no bridge or translation layer. That means little to no performance penalties. This also means that Ruby objects map to Objective-C objects without any extra work from you.
    - Since MacRuby 0.5’s release, they’ve supported Apple’s Grand Central Dispatch Library to support multi-core processors.
    - MacRuby is supposed to be Apple’s replacement for RubyCocoa.
    - Also, MacRuby 0.5 now has HotCocoa support, which I’ll briefly talk about later.

  • Originally, Macruby was called “Ruby+Objc” and was developed by Laurent Sansonetti. He started working on it in 2007. In March 2008 the first public version of MacRuby was released. In September of 2008 0.3 was released, which included the HotCocoa library, which allows you to develop interfaces using ruby. In March of this year MacRuby 0.4 was released.
  • - In MacRuby, Ruby types are nicely backed by foundation equivalents in Objective-C.
    - Here you can see the foundation counterparts of these Ruby classes.
  • - Going further, what we need to realize here is that all objects are objective-c objects, all classes are objective-c classes and all methods defined in a Ruby class are registered with the Objective-C runtime.
    - There were able to do this because of Core Foundation, which I mentioned before, which defines all of the primitive data types.
  • - Instead of using IRB you use MACIRB, which acts and performs the same way as IRB but for MacRuby.
    - So what I’m trying to show you here is that you use MacRuby the same way you would use traditional ruby.

    - All the Ruby types are backed by Foundation equivalents. Here you can see that instead of just a regular Ruby String object being shown, we get back an NSMutableString. Ruby classes like String are now just aliases to their Foundation counterparts.

    - Also, it’s because of this that we can still call the ruby string method “upcase” and call the NSMutableString method uppercaseString.
  • - So it’s also good to note that you can build objects by directly calling the Objective-C interface.
    - Here you can see us creating a new string by calling, stringWithString, and allocating and initializing with a string.
  • - Here you can see us easily creating an array just how we’re used to.
    - Also you scan ee that we get back an NSMutableArray instead of just a Ruby array.
    - The Array class descends from Ruby and Cocoa objects as well.
  • - This is an example that shows you what the method definition looks like in objective-c.
    - If you’re familiar with iPhone development, this is one of the callback methods of CoreLocation.
    - We can see here that the data types for each of the arguments that we need to pass in.
  • - The MacRuby version of this example is shown above.
    - It’s pretty close except that we removed the data types for each argument and it now looks more like idiomatic ruby with named arguments.
  • - If you were to try and call this method from MacRuby you could do the following with the named arguments and variables.
  • - Also, you can even call this method using key-value hash pairs, which could feel much more natural to you.
    - And remember that even though it looks like a hash, you have to make sure that the ordering stays the same.
  • - Interface Builder Outlets are essentially instance variables that refer to other objects.
    - When building graphical interfaces with our MacRuby application we need to be able to access our instance variables in Interface Builder so that we can make connections between our controller and our view.
    - We can do this by using attr_reader, attr_writer, or attr_accessor in MacRuby. In Objective-C we have to do the following below in red to create an IBOutlet in the header file.

  • - Interface Builder Actions are methods that we want to be called when a user performs a certain action on an object we specify within Interface Builder. Most commonly this would be a button that you could click on.
    - Also, by convention it is mandatory to have one parameter for these actions, which is noted above as sender. Sender specified in the method above would be the button that is clicked.
    - Without this sender parameter, Interface Builder will not register this action.
  • - After talking about all of the awesomeness of MacRuby some of you are probably wondering if you could ditch Objective-C and just write iPhone or iPad apps using MacRuby.
    - Sadly, you can’t yet. Apple doesn’t allow interpreted code and doesn’t support garbage collection for the iPhone OS.
    - Hopefully this will change but right now you’re going to have to stick with Objective-C. You could though, use tools like Appcelerator Titanium to create native apps using JavaScript.
    - If you’re interested in hearing about that please come see me after this talk - I’d love to talk about it.
  • - With MacRuby development you’ll spend a good chunk of time in XCode.
    - XCode is an IDE and I’m not sure how many people here use it but if you’re uncomfortable with it, you can still use your favorite text editor to work on your ruby files but you’ll have to come back to XCode to compile your application and run your application.
    - Xcode isn’t installed by default but it comes on that second disk you get with OSX and it’s also available for free online.
  • - You’ll also spend a good chunk of your time using Interface Builder, which is part of Xcode.
    - Interface builder allows for you to build the interfaces for your cocoa or macruby applications using a graphical user interface.
    - The files you work on are called NIB files which are our views.
  • - Also, with XCode you get great tools like Instruments.
    - Instruments allows you to profile your app, check for leaks, memory usage, cpu usage, see how many objects you create, and much more.
    - You get all of this when using MacRuby.

  • - What’s great about MacRuby is that it’s also got good support for testing
    - Any Ruby testing framework that you’d normally use can be used with MacRuby.
  • - So, the last thing I wanted to talk about was HotCocoa.
    - HotCocoa was developed by Rich Kilmer and it’s a thin Ruby layer that sits on top of Cocoa and other frameworks.
    - It was designed to simplify the way you can create user interfaces without using Interface Builder.
    - MacRuby 0.5 now supports HotCocoa and it’s included in MacRuby.
  • - Even though MacRuby allows us to write Cocoa apps using Ruby, if we want to programmatically create our interface we still have to implement the same Objective-C methods to create our UI and that can look a little nasty.
    - Below you can see how much nicer it is to do this using HotCocoa.
  • - This is how simple it is to use HotCocoa to programmatically construct your cocoa application.
    - What this does is create a window 100 pixels wide and 50 pixels tall and adds a button with the title ‘Hello’. Once you click this button it will spit out ‘World!’ to your console.
  • - Well, so MacRuby has a very exciting future ahead.
    - The current release is only at version 0.5 so there’s so much more that will surprise us before 1.0 is released.
    - Also, with Apple’s backing, soon everybody could be using Ruby to develop their Cocoa Desktop apps -- also possibly even for the iPhone and the iPad.
  • - And simply, it just allows you to use Ruby to develop Cocoa applications. How cool is that?
  • - MacRuby 0.5 is built upon the low level virtual machine (LLVM) in 0.5 but they used to use YARV
    - Switched from YARV to LLVM due to YARV’s lack of machine code compilation and the global interpreter lock, which prevented true concurrency.
    - MacRuby supports Just In Time and Ahead of Time compilation
    - AOT compilation makes MacRuby a true Ruby compiler

  • Mac ruby to the max - Brendan G. Lim

    1. 1. MAC RUBY Brendan G. Lim @brendanlim
    2. 2. WHO HERE HAS A MAC?
    5. 5. OBJECTIVE-C • Object-oriented extensions to C • Strongly typed • Like Ruby, influenced by Smalltalk • Primary language for Cocoa • Garbage collection (2.0) • 32 and 64-bit support
    6. 6. COCOA • Set of object-oriented frameworks • Used for writing Max OSX and iPhone OS apps • Includes FoundationKit, and AppKit • Typically built using tools like XCode and Interface Builder
    7. 7. CORE FOUNDATION • Low level libraries that ship with Mac OSX • Used for passing primitive types to OSX C routines • Most routines follow ‘CF’ naming convention • Open-Sourced by Apple as CF-Lite
    9. 9. RUBY VS OBJECTIVE-C object.method(param) = [object method:param];
    10. 10. RUBY VS OBJECTIVE-C person.set_name(“john”, “doe”) = [person setNameWithFirst:@”john” withLast:@”doe”];
    11. 11. RUBY VS OBJECTIVE-C array = [] = NSMutableArray *array = [[NSMutableArray alloc] init];
    12. 12. RUBY VS OBJECTIVE-C “ string”.strip = [@“ string” stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]
    13. 13. RUBY VS OBJECTIVE-C dictionary = {“key1” => “value1”, “key2” => “value2”} = NSArray *keys = [NSArray arrayWithObjects:@”key1”,@”key2”]; NSArray *data = [NSArray arrayWithObjects:@”value1”,@”value2”]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    14. 14. RUBYCOCOA • Mac OSX framework • Bridge between Objective-C and Ruby • Can manipulate Objective-C objects using Ruby • Write Cocoa apps in Ruby • Runs on Ruby 1.8 • Ships with OSX Leopard
    15. 15. RUBYCOCOA VS OBJECTIVE-C setObject_forKey_(iphone, phone) = [setObject:iphone forKey:phone];
    17. 17. WHY NOT RUBYCOCOA • Performance • Two runtimes • Two garbage collectors • Object conversions • Syntax doesn’t feel like Ruby
    18. 18. MAC RUBY +
    19. 19. MAC RUBY • Impl. of Ruby 1.9 that runs on the Objective-C runtime • Open sourced by Apple • Originally created by Laurent Sansonetti • Replacing RubyCocoa • Objects are peers with no translation layer • Multi-core (Grand Central Dispatch) • HotCocoa Support
    20. 20. MAC RUBY Object NSObject String NSMutableString Number NSNumber Array NSMutableArray Hash NSMutableDictionary
    21. 21. MAC RUBY Objects Objective-C Classes Objective-C Methods Objective-C
    22. 22. MAC RUBY >> s = “rubyconf” => “rubyconf” >> s.class => NSMutableString >> s.class.ancestors => [NSMutableString,NSString,Comparable,NSObject,Kernel] >> s.upcase => “RUBYCONF” >> s.uppercaseString => “RUBYCONF”
    23. 23. MAC RUBY >>“rubyconf”) => “rubyconf” >> NSString.stringWithString(“rubyconf”) => “rubyconf” >> NSString.alloc.initWithString(“rubyconf”) => “rubyconf”
    24. 24. MAC RUBY >> a = [] => [] >> a.class => NSMutableArray >> a.class.ancestors => [NSMutableArray,NSArray,Enumerable,NSObject,Kernel] >> a << “RubyConf” => [“RubyConf”]
    25. 25. MACRUBY VS OBJECTIVE-C -(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { }
    26. 26. MACRUBY VS OBJECTIVE-C def locationManager(manager didUpdateToLocation:newLocation fromLocation:oldLocation) end -(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { }
    27. 27. MACRUBY VS OBJECTIVE-C def locationManager(manager didUpdateToLocation:newLocation fromLocation:oldLocation) end >> locationManager(manager didUpdateToLocation:newLocation, fromLocation:oldLocation)
    28. 28. MACRUBY VS OBJECTIVE-C def locationManager(manager didUpdateToLocation:newLocation fromLocation:oldLocation) end >> locationManager(manager :didUpdateToLocation => newLocation, :fromLocation => oldLocation)
    29. 29. MACRUBY VS OBJECTIVE-C Interface Builder Outlets attr_accessor :my_string = # Interface (header file) NSString *myString; @property(nonatomic,retain) IBOutlet NSString *myString;
    30. 30. MACRUBY VS OBJECTIVE-C Interface Builder Actions def my_action(sender) ... end = # Interface -(IBAction) myAction:(id)sender; # Implementation -(IBAction) myAction:(id)sender { ... }
    32. 32. MAC RUBY Xcode
    33. 33. MAC RUBY Interface Builder
    34. 34. MAC RUBY Instruments
    35. 35. MAC RUBY Let’s build something ...
    36. 36. TDD IN MACRUBY • Good supports for tests • AnyRuby testing framework instantly becomes an Objective-C testing framework • Test::Unit • RSpec • Cucumber • etc...
    37. 37. HOTCOCOA • Use Ruby to build a UI without Interface Builder • Developed by Rich Kilmer • MacRuby 0.5 now supports HotCocoa • Packaged as a gem in MacRuby 0.5
    38. 38. MACRUBY VS HOTCOCOA win = NSWindow.alloc.initWithContentRect([10,20,300,300], :styleMask => (NSTitleWindowMask | NSCloseableWindowMask | NSMiniatureizableWindowMask | NSResizeableWindowMask) = win = window :frame => [10,20,300,300]
    39. 39. HELLO WORLD IN HOTCOCOA require ‘rubygems’ require ‘hotcocoa’ include HotCocoa application do |app| win = window :size => [100,50] b = button :title => ‘Hello’ b.on_action { puts ‘World!’ } win << b end
    40. 40. MAC RUBY Very exciting future
    41. 41. MAC RUBY It’s Ruby for Cocoa Apps!
    42. 42. MAC RUBY Questions?