easierbycode
3/14/2012 - 6:46 AM

mixins - class/instance properties and methods

mixins - class/instance properties and methods

# // http://arcturo.github.com/library/coffeescript/03_classes.html

# // We're going to define a class called Module that we can inherit from for mixin support. Module will have two static functions, @extend() and @include() which we can use for extending the class with static and instance properties respectively.

moduleKeywords = ['extended', 'included']

class Module
  @extend: (obj) ->
    for key, value of obj when key not in moduleKeywords
      @[key] = value

    obj.extended?.apply(@)
    this

  @include: (obj) ->
    for key, value of obj when key not in moduleKeywords
      # Assign properties to the prototype
      @::[key] = value

    obj.included?.apply(@)
    this

# // The little dance around the moduleKeywords variable is to ensure we have callback support when mixins extend a class. Let's take a look at our Module class in action:


classProperties = 
  find: (id) ->
  create: (attrs) ->

instanceProperties =
  save: -> 

class User extends Module
  @extend classProperties
  @include instanceProperties

# // Usage:
user = User.find(1)

user = new User
user.save()

# // As you can see, we've added some static properties, find() and create() to the User class, as well as some instance properties, save(). Since we've got callbacks whenever modules are extended, we can shortcut the process of applying both static and instance properties:


ORM = 
  find: (id) ->
  create: (attrs) ->
  extended: ->
    @include
      save: -> 

class User extends Module
  @extend ORM