Read the latest news on the Cappuccino reddit.

Tutorial on Adding Undo to Your Cappuccino Application Published on ThinkVitamin

November 13th, 2008

ThinkVitamin.com is featuring an article by Francisco that goes through the process of adding undo/redo support to an existing application. It uses a “furniture layout” application as the model, and goes through all the steps necessary to make user actions undoable.

This is a great demonstration of one of the powerful built-in features in Cappuccino, and a good read for anyone building an application in Cappuccino. Undo support is one of those features that goes a long way in making your application more enjoyable to use, and customers will love you for it.

So go checkout the tutorial, then get started adding undo support to your own applications!

Getting Started With Cappuccino and Ruby on Rails

November 11th, 2008

Cappuccino is completely server agnostic, meaning Cappuccino applications can be served using any HTTP server (for example Apache, lighttpd, Microsoft IIS, etc) and can communicate with any server side technology over HTTP (Ruby on Rails, Django, PHP, ASP, Java, CouchDB, etc). This lets you choose your server-side components based on whatever criteria is important to you (experience, existing infrastructure, etc).

That said, many people have asked for examples of using Cappuccino with various server side technologies, especially Ruby on Rails. Since Cappuccino is server agnostic, it turns out to be very simple to get started.

Setting Up a Project

The first step is to create your Rails project using the standard “rails appname” command:

rails appname
cd appname

Then create a new Cappuccino project in a temporary directory, either using the “steam create” command, or by downloading the “Starter Package”. Move the contents of the Cappuccino project to the Rails application’s “public” directory. Here’s an example using “steam create” (which will overwrite the default index.html):

steam create temp
mv temp/* public/.
rmdir temp

That’s it! Start the Rails webserver using “script/server”. Point your browser to http://localhost:3000/ and you should see the “hello world” Cappuccino application.

Exposing the Data

This alone isn’t particularly interesting. For Rails to be useful in conjunction with Cappuccino you’ll want to be able to transfer data between them. Rails makes this very easy.

Rails offers built in support for two common data exchange formats: JSON and XML. Of the two, JSON is typically prefered in Cappuccino. To output a Ruby data structure as JSON, simply call “render :json => object” in the controller action:


class TestController < ApplicationController
  def movies
    @movies = Movie.find(:all)
    render :json => @movies
  end
end

This is getting all the “Movie” model objects, and simply serializing the array into JSON.

You can also filter or process the array before serializing it. When an ActiveRecord instance is converted to JSON it is wrapped in an extra object that’s usually uneccessary (i.e. { “movie” : { “title” : “something”, “description” : “a description” }}). Creating a plain Ruby object from each ActiveRecord object prevents this. Additionally, it allows you to perform other processing, such as excluding certain properties. Here we use “map” to convert each ActiveRecord object to a plain Ruby object:


def movies
  @movies = Movie.find(:all).map {|m| { :title => m.title, :description => m.description } }
  render :json => @movies
end

Finally, if for some reason you need to use JSONP (be sure you understand why you need it, and the security implications!), Rails makes it very easy to wrap the JSON in callback:


def hello
	render :json => { :hello => "world" }, :callback => params[:jsoncallback]
end

This example also demonstrates accessing parameters that were passed in, namely the “jsoncallback” parameter.

Getting and Submitting Data From Cappuccino

The typical way to retrieve or submit data from a Cappuccino application is to use CPURLConnection. This is discussed extensively in a previous blog post, and all of it applies to using Cappuccino with Rails.

Scaffolding

In addition to HTML views Rails “scaffolding” also provides simple XML web services. You can also easily add JSON versions similar to the following:


def index
  @movies = Movie.find(:all)

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @movies }
    format.json  { render :json => @movies }
  end
end

Conclusion

This covers the bare essentials of integrating a Cappuccino application with Rails. There is lots of potential for better Cappuccino integration with ActiveRecord and other server-side data technologies. Please feel free to make suggestions, or implement something and contribute it back!

Web Directions North

November 8th, 2008

In February, we’ll be running a workshop at the Web Directions North conference in Denver. It will be a four hour workshop on getting started with Cappuccino and Objective-J.

Here’s a blurb about the workshop:

This workshop will get you started on building applications in Cappuccino and Objective-J. Attendees will not be expected to have any prior experience with these technologies, but some familiarity with JavaScript and Object Oriented concepts are recommended. By the end of the workshop you will be comfortable with Objective-J and have worked through the process of building a simple application in Cappuccino. You’ll be introduced to common patterns, the most used classes, and you’ll learn how to find new information as you need it.

If you’re interested in attending the conference, or even just the workshop, you can use this discount code: WDN09RB. This will get you $50 off, making the conference $745 before December 14th, or the standalone workshop $195.

Here’s some marketing content directly from Web Directions:

Web Directions is a highly focussed conference and workshops for web designers, developers, UX and ID designers, and other web professionals whose day to day job is building web sites and web applications. It features two dozen world class experts, with a razor sharp focus on practical techniques and technologies you can use right away to build even better sites.

http://north.webdirections.org/

Web Directions North features

  • 8 half day workshops
  • the brand new full day Ed Directions North, for those teaching web professionals
  • a two track, two day conference, featuring over 20 sessions

New Cappuccino Automatic Layout Tutorial

November 7th, 2008

This new tutorial covers Cappuccino’s powerful system of automatic resizing and repositioning support for creating dynamic layouts easily and quickly.  Proper resizing behavior is an important part of polishing any application, so make sure to check it out!

Cappuccino Tools: “bake”

October 29th, 2008

In the final installment of the Cappuccino Tool article series (for now), we cover “bake”, an automatic deployment tool. Writing a Cappuccino application does not require using “bake”, but can help with more advanced deployments.

Introduction

“bake” is somewhat analogous to Capistrano, a deployment tool often used for deploying Ruby on Rails and other applications, but “bake” has several features specifically for deploying Cappuccino applications.

The basic idea behind “bake” is to assemble a complete deployable copy of your application by pulling the pieces from various places (Git, Subversion, and local or remote directories via rsync), building it, packing it up, and deploying it to your server(s).

One key feature of bake is the management of multiple deployments over time, which allows three things: atomic deployments, keeping your client side code (the Cappuccino application) synchronized with your server side code, and enabling aggressive caching on all your static resources (code, images, etc). We’ll see later this is done by putting all the new resources in place, then “swinging” a single file, the index.html with a <base> tag.

“Atomic deployments” means that the deployment is updated to the new version in a single operation, which is either successful or not, nothing in between. Every client loading your application receives either the previous deployment, or the new deployment, but never a mixture of the two.

Keeping client code synchronized with server code is (sometimes) important for making sure users who have already loaded the application can continue using it even after you deploy a new version of the server side code that is incompatible with older versions of the client side code.

Aggressive caching of static resources reduces the load time of Cappuccino applications for repeat useres. This is possible because every resources URL is unique in each deployment, so we can set the “Expires” header far in the future (e.x. ‘Expires “Thu, 15 Apr 2010 20:00:00 GMT”‘). While the actual file name is not unique (for example Objective-J/Objective-J.js), in the deployed application the path will be unique (www.yourserver.com/YourApp/1225273279/Objective-J/Objective-J.js where the version number changes for each deployment)

Summary

The configuration for a bake deployment is specified in a “bakefile”, which is in the JSON format with a structure like the following:

{
	"sources" : [
	    {
	        "type"    : "git",
	        "path"    : "git://github.com/280north/cappuccino.git",
	        "parts"   : [
    	        {
    	            "src"       :   "Objective-J",
    	            "dst"       :   "Frameworks/Objective-J",
    	            "build"     :   "ant -DBuild=BUILD_PATH",
    	            "copyFrom"  :   "Release/Objective-J"
    	        },
	            {
    	            "src"       :   "Foundation",
    	            "dst"       :   "Frameworks/Foundation",
    	            "build"     :   "steam build -c Release -b BUILD_PATH",
    	            "copyFrom"  :   "Release/Foundation"
	            },
        	    {
    	            "src"       :   "AppKit",
    	            "dst"       :   "Frameworks/AppKit",
    	            "build"     :   "steam build -c Release -b BUILD_PATH",
    	            "copyFrom"  :   "Release/AppKit"
        	    }
	        ]
	    },
	    {
	        "type"    : "rsync",
	        "path"    : "/Users/username/projects/NewApplication",
	        "parts"   : [
	            {
    	            "src"       :   "",
    	            "dst"       :   "Blah"
	            }
	        ]
	    },
	    {
	        "type"    : "svn",
	        "path"    : "https://svn.youserver.com/Project/trunk",
	        "parts"   : [
	            {
    	            "src"       :   "subdirectory",
    	            "dst"       :   "Something"
	            }
	        ]
	    }
	],
	"deployments" : [
	    { "host" : "deploy@myserver.com", "path" : "/var/www/mysite/public" }
	],
	"templateVars" : {
        "APPLICATION_NAME" : "My Application",
        "BACKGROUND_COLOR" : "black",
        "TEXT_COLOR" : "black"
	}
}

This bakefile contains three “sources”: a git repository, a local directory, and a svn repository. The git repository is the main Cappuccino git repository, hosted on GitHub. You could replace this with a different branch if you needed a specific version, or even your own if you have one. This source contains three “parts”, Objective-J, AppKit, and Foundation. The “src” specifies where in the checkout the part is located, while “dst” specified where in the final built application it should be placed. You can optionally specify a “build” command, which is run from the specified “src” directory. This command should include the placeholder “BUILD_PATH”, which will be filled in by “bake” with the temporary directory where the build results are placed (equivalent to $STEAM_BUILD for any “steam” commands). Additionally, if you specify a “build” command you also need to specify a “copyFrom” parameter, which tells build the subdirectory of the build directory it should copy the built part from.

Once each piece of the application has been built it is copied to the appropriate subdirectory of a uniquely named (using the current Unix timestamp) “versioned” directory. Rather than deploying this versioned directory directly, it is placed within another directory which contains a special index.html file. This file includes a <base> tag that points to the versioned directory, which causes the browser to treat it as the base for all relative URLs, thus loading the correct version of all resources without requiring the application be located at a unique URL. “bake” will fill in “$VERSION” template variable in the base tag of the template with the correct

Additionally, “bake” will calculate the size of all code which needs to be loaded, in order to provide an accurate loading progress bar. The calculated size is inserted into the template variable “$FILES_TOTAL”. You can also specify other template variables such as “$APPLICATION_NAME”, “$BACKGROUND_COLOR”, and “$TEXT_COLOR” in the bakefile.

If you use your own template, the only required variable is the “$VERSION” one, but you can specify as many custom variables as you wish.

Finally, once the application has been built and assembled, it is optionally run through “press”, then gzipped. If the “–deploy” command line parameter was given then the gzipped application is transmitted to the deployment servers, un-gzipped, and copied to the deployment path using a specific sequence of command to ensure the deployment is atomic:

tar xzf 1225273279.tar.gz
mkdir -p /path/to/deployment
mv 1225273279/1225273279/ /path/to/deployment/1225273279
mv 1225273279/index.html path/to/deployment/index.html
rm "1225273279.tar.gz
rmdir 1225273279
cd /path/to/deployment
ln -nsf 1225273279 Current

(version “1225273279″, deplyoment directory “/path/to/deployment”)

One important thing to note about “bake” is that since the old deployment remains live (but hidden) if you deploy a fix for a security vulnerability you should manually purge all the old deployments from your server. If the change doesn’t introduce any incompatibilities between the server and client, you could set up a rewrite rule to direct all requests to the purged deployments to the latest, which is always symlinked to “Current”.

Conclusion

Once again I should stress that this tool is by no means required for writing a Cappuccino application. It was written to help deploy our production application, 280 Slides, but we have made it available for anyone who has similar deployment requirements. If it doesn’t quite fit your requirements, please feel free to suggest improvements, or even better, make improvements yourself and contribute them back!

Synthesizing Accessor Methods

October 26th, 2008

Yesterday, Francisco and Tom checked in a new feature to the Cappuccino git repository, called accessor synthesizing. This is a new language feature for Objective-J, and its designed to reduce the amount of boilerplate code developers have to write in a custom class. Normally, when you write a custom class in Objective-J, you also write a pair of getter and setter methods for each instance variable (ivar) that you want to expose. This usually means writing repetitive code that hardly ever changes each time you write it. With accessor synthesizing, developers will only have to write getter and setter methods when something truly interesting needs to happen in those methods.

Accessor synthesizing adds a new keyword to the Objective-J language, @accessors. When declaring your list of ivars in the @implementation block of your class, adding this one keyword will tell the Objective-J preprocessor to implement accessors for you. Let’s see an example of a simple class written using the old method, and then the same class using @accessors.

This Person class has two ivars, firstname and lastname. Before @accessors, the class looks like this:


@implementation Person : CPObject
{
    CPString firstName;
    CPString lastName;
}

- (void)setFirstName:(CPString)aString
{
    firstName = aString;
}

- (CPString)firstName
{
    return firstName;
}

- (void)setLastName:(CPString)aString
{
    lastName = aString;
}

- (CPString)lastName
{
    return lastName;
}

@end

Using the new @accessors keyword, we can eliminate four methods:


@implementation Person : CPObject
{
    CPString firstName @accessors;
    CPString lastName @accessors;
}
@end

This second version is much more succinct than the first, and less tedious to program. We think this will be helpful for developers, and will increase productivity and code readability.

It’s important to note that this doesn’t change the way you use a class. For our Person class, in both cases, the code for getting the first and last names of a person (in the myPerson variable) would look something like this:


var fullName = [myPerson firstName] + " " + [myPerson lastName];

Similarly, setting an ivar looks like this:


[myPerson setFirstName:"Winston"];
[myPerson setLastName:"Smith"];

Like any key-value-coding compliant class, the name of the instance variable becomes the “property” or “key”, and that key name is used in the setter and getter methods. If your key is firstName, the getter for that key will be firstName, and the setter will be setFirstName:. The same pattern applies to any other key.

Configuration

There are a few configuration options when using the new @accessors technique. Perhaps most importantly, is the ability to change the name of the property. For example, if you declared an instance variable like this:


CPString _location @accessors;

Objective-J would generate two accessor methods called _location and _setLocation:. These are the expected accessor methods for a key called “_location”. In order to generate more friendly versions without the leading underscore, you can modify your declaration like this:


CPString _location @accessors(property=location);

The addition of the property=location tells Objective-J to use “location” as the new property name, instead of “_location”, which will generate location and setLocation: methods without the underscore. In addition, you can also specify the specific name of both the getter and the setter method, like this:


BOOL _hidden @accessors(getter=isHidden, setter=setIsHidden);

This code specified a boolean instance variable called _hidden; the getter method will be called isHidden and the setter method will be called setIsHidden:. One thing to keep in mind when specifying your own getter and setter method names is key-value-coding. Although we don’t yet have much documentation on the subject (you can read Apple’s documentation here), key-value-coding enables several important features in Cappuccino, so it’s important to maintain key-value-coding compliance. Normally, the rules are that for a given key, say “foo”, the getter is called foo, and the setter is called setFoo:. There’s an additional rule for boolean values, which says that you can use isFoo, and setIsFoo:, in addition to the usual method names. In our case, thats why our custom getter and setter names are still key-value-coding compliant.

There are two additional configuration options, readonly, and copy. By default, @accessors will generate both a getter and a setter. If you only want to expose a getter method to the world, you can add the readonly value in the arguments. The other option, copy, has to do with how the setter works. Normally, when you pass an object to a setter, it’s assigned directly. The generated setter looks like this:


- (void)setFoo:(id)aFoo
{
    foo = aFoo;
}

When you specify copy, the argument is first sent the message copy, and the return value of that message is assigned to the instance variable:


- (void)setFoo:(id)aFoo
{
    if (foo !== aFoo)
        foo = [aFoo copy];
}

This is useful if you want to ensure that an object you’re passing isn’t modified out from under you. Of course, it only applies to ivars that are both read and write, and cannot be combined with readonly. To summarize, you can use both of these options like this:


@implementation FooBar : CPObject
{
    id foo @accessors(readonly);
    id bar @accessors(copy);
}

History

Apple introduced properties in Objective-C 2.0, which added a new way to declare instance variables for your classes. The two key features were the ability to use what has become known as “the dot syntax” for accessing instance variables, and the second was the ability to have the compiler automatically generate accessor methods. Reducing code, especially code that doesn’t change every time you write it, is certainly a worthwhile goal, so we thought it would be a good idea to bring this new idea to Objective-J. There are a lot of things about the Objective-C 2.0 implementation of properties that don’t make sense for Objective-J, so we decided not to port them directly and instead developed a syntax that we believe makes the most sense.

The main goal we want to achieve is eliminating the need to write your own accessor methods. We don’t, however, support the “dot syntax” aspect of Objective-C 2.0. This makes the dual @property and @synthesize syntax of Objective-C 2.0 redundant. Furthermore, rather than just choose one or the other, we decided to use a new keyword, @accessors. This will lesson the confusion for existing Cocoa developers trying to learn Objective-J. It will also make sure we don’t have an incompatible syntax going forward, as we explore new ways to work with existing Objective-C code.

Conclusion

Accessor synthesizing will reduce the amount of boilerplate code that needs to be written, and make the language just a little bit easier to develop in. Overall, we think it’s a worthwhile addition to the language. If you have an opinion, we’d love to hear it, so sound off in the comments. Although this new syntax isn’t yet written in stone, we won’t expect to change it after version 0.6 of Cappuccino ships. Checkout the latest version of the git repository to start using this new feature.

We’re also considering other language features that might make it easier to program in Objective-J. If you’ve got an idea, or you’re interested in being part of the discussion, you should sign up for the mailing list, where we’ll be discussing some of the new proposals.

Download

Cappuccino and Objective-J are licensed under the LPGL. For more information, see our licensing page.

Copyright © 2008 - 280 North, Inc. Cappuccino and Objective-J are registered Trademarks of 280 North. Logo by Sofa.