Skip to content

Instantly share code, notes, and snippets.

@bremac
Created May 30, 2011 13:47
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 bremac/998920 to your computer and use it in GitHub Desktop.
Save bremac/998920 to your computer and use it in GitHub Desktop.
Hal-baked ideas on Injectors. All legal but unusual coffee-script
inspect = (o) ->
alert(JSON.stringify(o))
# GWT-style module injection
class Module
constructor: (m) ->
@extend(m)
extend: (m) ->
for k, v of m
@[k] = v
@
create: (type) ->
@inject(new type(), type.INJECTED)
inject: (obj, dict) ->
if dict?
for name, factory of dict
obj[name] = @[factory](@)
obj
main = new Module
Foo: -> 'FOO FACTORY RESULT'
Bar: -> 'BAR FACTORY RESULT'
class Baz
@INJECTED =
foo: 'Foo'
bar: 'Bar'
myBaz = main.create(Baz)
# Monkey-patching interface
class Interface
NOT_IMPLEMENTED = -> throw 'not implemented'
__impl__: NOT_IMPLEMENTED
constructor: ->
@__impl__()
@use: (type) ->
unless @::__impl__ is NOT_IMPLEMENTED
throw 'Rebinding of bound interface attempted'
@::__impl__ = type
for k, v of type
@[k] = v
for k, v of type::
@::[k] = v
@
class Foo extends Interface
usesFoo = ->
f = new Foo()
f.hi()
class Bar
constructor: ->
@greeting = 'Hello'
hi: -> alert('hi')
Foo.use(Bar)
f = new Foo()
f.hi()
alert(f.greeting)
# Of course, usesFoo works too:
usesFoo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment