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.

<span class="mw-page-title-main">GNUstep</span> 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.

<span class="mw-page-title-main">WebObjects</span> Java web application server and framework originally developed by NeXT Software

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

In object-oriented programming, a metaclass is a class whose instances are classes themselves. Unlike ordinary classes, which define the behaviors of objects, metaclasses specify the behaviors of classes and their instances. Not all object-oriented programming languages support the concept of metaclasses. For those that do, the extent of control metaclasses have over class behaviors varies. Metaclasses are often implemented by treating classes as first-class citizens, making a metaclass an object that creates and manages these classes. Each programming language adheres to its own metaobject protocol, which are the rules that determine interactions among objects, classes, and metaclasses. Metaclasses are utilized to automate code generation and to enhance framework development.

<span class="mw-page-title-main">AppKit</span> 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 implementation of the AppKit API.

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.

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field and a method. The syntax for reading and writing of properties is like for fields, but property reads and writes are (usually) translated to 'getter' and 'setter' method calls. The field-like syntax is easier to read and write than many method calls, yet the interposition of method calls "under the hood" allows for data validation, active updating, or implementation of what may be called "read-only fields".

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 high-level 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. Due to Apple macOS’s direct lineage from NeXTSTEP, Objective-C was the standard programming language used, supported, and promoted by Apple for developing macOS and iOS applications until the introduction of the Swift programming language 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 high-level general-purpose, multi-paradigm, compiled programming language created by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

References