Skip to content

Instantly share code, notes, and snippets.

@hashmal
Created January 31, 2011 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hashmal/803816 to your computer and use it in GitHub Desktop.
Save hashmal/803816 to your computer and use it in GitHub Desktop.
Playing with CoffeeScript, do funny things with mixins.
# Swappable Mixins in CoffeeScript
# ================================
# This is experimental. Not tested. It's just a toy, and I'm very new to
# javascript/coffeescript. Be warned.
# Usage
# -----
# class MyMixin extends Mixin
# foo: ->
#
# obj = {bar: ->}
#
# MyMixin:: augment obj
#
# obj.foo # -> [function]
# obj.bar # -> [function]
#
# obj.eject MyMixin
#
# obj.foo # -> undefined
# obj.bar # -> [function]
# Mixin
# -----
# Classes inheriting `Mixin` will become removable mixins, enabling you to
# swap them around.
class Mixin
# "Class method". Augment object or class `t` with new methods.
augment: (t) ->
(t[n] = m unless n == 'augment' or !this[n].prototype?) for n, m of this
# When an object is augmented with at least one mixin, call this method to
# remove `mixin`.
eject: (mixin) ->
(delete this[n] if m in (p for o, p of mixin::)) for n, m of this
# Limitations
# -----------
# * When a class is augmented, all instances of that class are augmented too,
# and when a mixin is ejected from a class, all instances lose that mixin
# too.
# * You can't eject a mixin from an object if that mixin was added to the
# object's class. Eject the mixin from the class instead.
# * Only methods can be mixed-in, attributes are ignored.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment