RubyCocoa

Last updated

RubyCocoa is a macOS framework that provides a bridge between the Ruby and the Objective-C programming languages, allowing the user to manipulate Objective-C objects from Ruby, and vice versa. It makes it possible to write a Cocoa application completely in Ruby as well as to write an application that mixes Ruby and Objective-C code. An Apple project called MacRuby was under development to replace RubyCocoa in 2008. A proprietary spin-off called RubyMotion was subsequently released in 2012, available for iOS, macOS and Android.

Contents

Some useful applications of RubyCocoa are exploration of a Cocoa object's features with irb interactively, prototyping of a Cocoa application, writing a Cocoa application that combines the features of Ruby and Objective-C and wrapping macOS' native GUI for a Ruby script.

RubyCocoa is free software, released under both the Ruby License and the LGPL.

History

RubyCocoa was started in 2001 by Hisakuni Fujimoto when he implemented a Ruby extension module to wrap NSObject and NSClassFromString function. Later it was integrated with Project Builder (which later became Xcode). In 2002 the project was registered on SourceForge and the development team began to grow.

In 2006 the committers list was first joined by a developer from Apple, Laurent Sansonetti, and then a RubyCocoa presentation was made during WWDC. Apple stated that RubyCocoa will be included and supported in Mac OS X v10.5 “Leopard”.

In August 2008, Sansonetti confirmed that MacRuby "is supposed to replace RubyCocoa." in the future.

How does the bridge work?

RubyCocoa is sometimes interpreted as a set of bindings to the Cocoa frameworks, which is false. RubyCocoa is a real bridge between the Objective-C and Ruby programming languages.

Lazy class import

RubyCocoa will import the Objective-C classes into the Ruby world on demand. For example, when you access OSX::NSTableView for the very first time in your code, RubyCocoa will retrieve all the necessary information regarding this class from the Objective-C runtime and create a Ruby class of the same name that will act as a proxy. It will also import in the same way all the inherited classes.

Forwarding messages

As stated earlier, RubyCocoa creates special proxy objects. Every time you send a Ruby message to a proxy object, RubyCocoa will try to forward it to the embedded Objective-C instance, by translating the message name to an Objective-C selector and asking the Objective-C runtime to forward it.

If an exception is raised from the Objective-C world, RubyCocoa will convert it to a Ruby exception and forward it to you.

RubyCocoa uses the libffi library to call the Objective-C methods implementations.

Automatic method overriding

RubyCocoa makes it easy to override an Objective-C method from Ruby, either in a subclass or directly to the class (as you would do in Objective-C using a category).

Once your method is inserted, RubyCocoa will retrieve the signature of the existing Objective-C method and inject a new one to the Objective-C runtime, of the same signature, but which now points to your code.

To accomplish this, RubyCocoa uses the libffi library to dynamically create a closure that will call the Ruby method, and just passes a pointer to that new closure to the Objective-C runtime.

Accessing the C bits

Due to the nature of the Objective-C language, you can freely use C from Objective-C code. In order to bridge the relevant C parts of an Objective-C framework, such as C structures, functions, enumerations, constants and more, RubyCocoa relies on the BridgeSupport project.

RubyCocoa will interpret at runtime the BridgeSupport files (using the very fast libXML2's xmlTextReader) and accordingly handle their content. It will for instance construct the Ruby proxy classes for the C structures and also create the functions.

Note that the costly operations, such as localizing the symbols, are done on demand, and obviously only once.

Format strings

RubyCocoa is able to detect APIs that use format strings, like NSLog or NSString.stringWithFormat, and appropriately convert the variable arguments to the types specified in the format string.

Function pointers

RubyCocoa allows you to pass Ruby Proc objects as function pointer arguments. It will then use the libffi library to dynamically create a closure and pass it to the underlying function/method.

Creation of Cocoa applications written in Ruby

Installing RubyCocoa also automatically installs the corresponding Xcode templates. This allows developers to select "Cocoa-Ruby Application" as the Xcode project type and Xcode will generate all necessary files for them.

How to call Objective-C methods from Ruby

To invoke an Objective-C method, you replace each colon in the method name except the last with an underscore. Thus, for example, the NSWindow instance method initWithContentRect:styleMask:backing:defer: becomes initWithContentRect_styleMask_backing_defer.

All Cocoa classes and functions belong to OSX module, so for example, the Objective-C code:

[[NSWindowalloc]initWithContentRect:framestyleMask:NSTitledWindowMaskbacking:NSBackingStoreBuffereddefer:NO]

will become:

OSX::NSWindow.alloc.initWithContentRect_styleMask_backing_defer(frame,OSX::NSTitledWindowMask,OSX::NSBackingStoreBuffered,false)

As you can see, this decreases the code readability by rendering Objective-C parameter naming useless. So, there is another convenient way to write the method calls — the objc_send method, which accepts Ruby symbols as parameter names. For example, the previous code can also be written as:

OSX::NSWindow.alloc.objc_send(:initWithContentRect,frame,:styleMask,OSX::NSTitledWindowMask,:backing,OSX::NSBackingStoreBuffered,:defer,false)

Advantages of RubyCocoa

Disadvantages

Related Research Articles

Cocoa is Apple's native object-oriented application programming interface (API) for its desktop operating system macOS.

GNUstep Open source widget toolkit and application development tools

GNUstep is a free software implementation of the Cocoa Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project.

Carbon was one of two primary C-based application programming interfaces (APIs) developed by Apple for the macOS operating system. Carbon provided a good degree of backward compatibility for programs that ran on Mac OS 8 and 9. Developers could use the Carbon APIs to port (“carbonize”) their “classic” Mac applications and software to the Mac OS X platform with little effort, compared to porting the app to the entirely different Cocoa system, which originated in OPENSTEP. With the release of macOS 10.15 Catalina, the Carbon API was officially discontinued and removed, leaving Cocoa as the sole primary API for developing macOS applications.

In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.

WebObjects Java web application server and framework originally developed by NeXT Software

WebObjects is a Java web application server and a server-based web application framework originally developed by NeXT Software, Inc.

Xcode IDE including tools for developing software for Apple platforms

Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 13.4.1, released on June 2, 2022 via the Mac App Store with macOS Monterey. The software suite is offered free of charge. Registered developers can download preview releases and prior versions of the suite through the Apple Developer website. Xcode includes command-line tools which enable UNIX-style development via the Terminal app in macOS. They can also be downloaded and installed without the GUI.

In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses. Among those that do, the extent to which metaclasses can override any given aspect of class behavior varies. Metaclasses can be implemented by having classes be first-class citizens, in which case a metaclass is simply an object that constructs classes. Each language has its own metaobject protocol, a set of rules that govern how objects, classes, and metaclasses interact.

AppKit Graphical user interface toolkit

AppKit is a graphical user interface toolkit. It initially served as the UI framework for NeXTSTEP. Along with Foundation and Display PostScript, it became one of the core parts of the OpenStep specification of APIs. Later, AppKit and Foundation became part of Cocoa, the Objective-C API framework of macOS. GNUstep, GNU's implementation of the OpenStep/Cocoa API, also contains an AppKit.

Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows data organized by the relational entity–attribute model to be serialized into XML, binary, or SQLite stores. The data can be manipulated using higher level objects representing entities and their relationships. Core Data manages the serialized version, providing object lifecycle and object graph management, including persistence. Core Data interfaces directly with SQLite, insulating the developer from the underlying SQL.

PyObjC is a bidirectional bridge between the Python and Objective-C programming languages, allowing programmers to use and extend existing Objective-C libraries, such as Apple's Cocoa framework, using Python.

The Apple Developer Tools are a suite of software tools from Apple to aid in making software dynamic titles for the macOS and iOS platforms. The developer tools were formerly included on macOS install media, but are now exclusively distributed over the Internet. As of macOS 10.12, Xcode is available as a free download from the Mac App Store.

Dynamic loading is a mechanism by which a computer program can, at run time, load a library into memory, retrieve the addresses of functions and variables contained in the library, execute those functions or access those variables, and unload the library from memory. It is one of the 3 mechanisms by which a computer program can use some other software; the other two are static linking and dynamic linking. Unlike static linking and dynamic linking, dynamic loading allows a computer program to start up in the absence of these libraries, to discover available libraries, and to potentially gain additional functionality.

Nu is an interpreted object-oriented programming language, with a Lisp-like syntax, created by Tim Burks as an alternative scripting language to program OS X through its Cocoa application programming interface (API). Implementations also exist for iPhone and Linux.

MacRuby is a discontinued implementation of the Ruby language that ran on the Objective-C runtime and CoreFoundation framework under development by Apple Inc. which "was supposed to replace RubyCocoa". It targeted Ruby 1.9 and used the high performance LLVM compiler infrastructure starting with version 0.5. It supports both ahead-of-time and just-in-time compilation.

RemObjects Software is an American software company founded in 2002 by Alessandro Federici and Marc Hoffman. It develops and offers tools and libraries for software developers on a variety of development platforms, including Embarcadero Delphi, Microsoft .NET, Mono, and Apple's Xcode.

International IT University or International university of information technologies - established in close collaboration with educational organization iCarnegie which represents American IT university Carnegie Mellon in 2009 by order of President of Kazakhstan. Formation of the qualified, international recognized IT specialists in Kazakhstan became the purpose of creation of a higher educational institution of a similar profile. International IT University provided with grants from the government of Kazakhstan and national infocommunication companies, which cover disciplines by Kazakhstan and the U.S. educational systems.

Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift programming languages. At compile time, it inserts into the object code messages retain and release which increase and decrease the reference count at run time, marking for deallocation those objects when the number of references to them reaches zero.

Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Objective-C was the standard programming language supported by Apple for developing macOS and iOS applications using their respective application programming interfaces (APIs), Cocoa and Cocoa Touch, until the introduction of Swift in 2014.

In computer science, bridging describes systems that map the runtime behaviour of different programming languages so they can share common resources. They are often used to allow "foreign" languages to operate a host platform's native object libraries, translating data and state across the two sides of the bridge. Bridging contrasts with "embedding" systems that allow limited interaction through a black box mechanism, where state sharing is limited or non-existent.

Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. First released in 2014, Swift was developed as a replacement for Apple's earlier programming language Objective-C, as Objective-C had been largely unchanged since the early 1980s and lacked modern language features. Swift works with Apple's Cocoa and Cocoa Touch frameworks, and a key aspect of Swift's design was the ability to interoperate with the huge body of existing Objective-C code developed for Apple products over the previous decades. It was built with the open source LLVM compiler framework and has been included in Xcode since version 6, released in 2014. On Apple platforms, it uses the Objective-C runtime library, which allows C, Objective-C, C++ and Swift code to run within one program.