Declarative Models in CoffeeScript
_ _ _ ___ _ _ _ _ /_\ | |_ __ ___ __| |_ / _ \| |__ ___ ___| |___| |_ ___ _ _ ___| |_ / _ \| | ' \/ _ (_-< _| (_) | '_ (_-</ _ \ / -_) _/ -_)_| ' \/ -_) _| /_/ \_\_|_|_|_\___/__/\__|\___/|_.__/__/\___/_\___|\__\___(_)_||_\___|\__| In Glorious ASCII-VISION
Summary: I've come across a nice way of using CoffeeScript class syntax to make declarative models, examples below. A more complete implementation is in a Gist here.
Declarative Models in CoffeeScript
I've been playing with a nice way of defining models in a sort of declarative way in CoffeeScript, this is what I have so far:
Which would be used like this:
I'm currently using something like this for an MVC architected iPhone App written in CoffeeScript. I wanted a way of defining fields and relationships in a simple, expressive and DRY way.
It works using class methods on the Model base class (as described at the end of Class section in the CoffeeScript docs). This works because the body of a class in CoffeeScript is executable code and within the body @ refers to the class object itself (elsewhere it refers to the current value of 'this').
For example, a partial implementation of the Model class (just defining @field and not including events, see here for a more complete implementation) would be:
A more complete implementation (with support for everything in the example I showed at the top) is in this Gist.
The "field" class method stores information about the field in the class property named 'fields'. The constructor then uses this information to construct model instances.
This is just what I've implemented so far, I'll probably do JSON serialisation and de-serialisation next. I've taken the get/set method style from Backbone (which although I'm not using it here is great, I may write a declarative layer on top of it at some point). A much nicer syntax that would remove the need for the get and set methods could be got by using defineProperty but that would limit compatibility (it wouldn't work on Opera or IE 8, it would be fine for Node.JS though).
Overall I really like this use of CoffeeScript classes. I think it would make a great base for an ORM. I'll probably post something more complete to GitHub soon. I'm sure there are loads of other uses for this style too!
_______________________________________ < follow me on Twitter: @almostobsolete > --------------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ | | ----w | || || ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^