Skip to content

Instantly share code, notes, and snippets.

@keithnorm
Created December 31, 2014 17:21
Show Gist options
  • Save keithnorm/8b7496eb2dd5c23c62d5 to your computer and use it in GitHub Desktop.
Save keithnorm/8b7496eb2dd5c23c62d5 to your computer and use it in GitHub Desktop.
A JavaScript implementation of the Rails delegate class method (kind of)
class Delegator
@delegate: []
constructor: ->
for delegate in @constructor.delegate
target = delegate[delegate.length - 1].to
for attribute in delegate when not attribute.to
property = {}
if /\(\)$/.test attribute
funcName = attribute.substring 0, attribute.length - 2
@[funcName] = (->
_funcName = funcName
->
@[target][_funcName]()
)()
else
property[attribute] =
get: (->
name = attribute
->
@[target][name]
)()
Object.defineProperties @, property
class MyThing extends Delegator
@delegate: [
['foo', to: 'bar']
]
constructor: (@bar) ->
super
bar = {foo: 'foobar'}
myThing = new MyThing(bar)
myThing.foo # 'foobar'
# Anyway, that's the idea of it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment