Playing with CoffeeScript, do funny things with mixins.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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