Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created April 12, 2012 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancejpollard/2365817 to your computer and use it in GitHub Desktop.
Save lancejpollard/2365817 to your computer and use it in GitHub Desktop.
Customize how a class is constructed by customizing CoffeeScript compiler output

CoffeeScript Now

Input

class BaseClass

class Model extends BaseClass
  @aClassVariable: false
  @aClassMethod: ->
  anInstanceVariable: false
  anInstanceMethod: ->

  @aClassMethod()

Current Output

var __hasProp = Object.prototype.hasOwnProperty,
  // 0. extends is defined.
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Model = (function(_super) {
  // 1. call to extends...
  __extends(Model, _super);
  
  // 2. all class variables
  Model.aClassVariable = false;

  // 3. all class methods
  Model.aClassMethod = function() {
    
  };
  
  // 4. define constructor
  function Model(attributes, options) {
    // if `super` was called, then add this
    Model.__super__.constructor.apply(this, arguments);
  }
  
  // 5. all instance variables
  Model.prototype.anInstanceVariable = false;

  // 6. all instance methods
  Model.prototype.anInstanceMethod = function() {
    
  };

  // 7. executable class body
  Model.aClassMethod();
  
  // return constructor
  return Model;
  
  // pass in superclass
})(BaseClass);

Desired Output

The desired output should not define the __extend method, but it should have a hook of some sort.

var __hasProp = Object.prototype.hasOwnProperty;

Model = (function(_super) {
  // 1. define constructor (Ember and others can create base class here)
  var Model = __extend(_super)
  
  // 2. define class variables and methods
  Model.reopenClass({
    aClassVariable: false,
    
    aClassMethod: function() {
      
    }
  });
  
  // 3. define instance variables and methods
  Model.reopen({
    anInstanceVariable: false,
    
    anInstanceMethod: function() {
      
    }
  });

  // executable class body
  Model.aClassMethod();
  
  // 4. return constructor
  return Model;

})(BaseClass);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment