Instantly share code, notes, and snippets.

Embed
What would you like to do?
class X.Example extends X.Object
@proxyMethod "attachmentManager.manageAttachment"
# Equivalent to:
# manageAttachment: ->
# @attachmentManager.manageAttachment.apply(@attachmentManager, arguments)
@proxyMethod "delegate?.compositionDidChangeDocument"
# Equivalent to:
# compositionDidChangeDocument: ->
# @delegate?.compositionDidChangeDocument?.apply(@delegate, arguments)
@proxyMethod "getSelectionManager().getLocationRange"
# Equivalent to:
# getLocationRange: ->
# selectionManager = @getSelectionManager()
# selectionManager.getLocationRange.apply(selectionManager, arguments)
class X.Object
@proxyMethod: (expression) ->
{name, toMethod, toProperty, optional} = parseProxyMethodExpression(expression)
@::[name] = ->
object = if toMethod?
if optional then @[toMethod]?() else @[toMethod]()
else if toProperty?
@[toProperty]
if optional
object?[name]?.apply(object, arguments)
else
object[name].apply(object, arguments)
parseProxyMethodExpression = (expression) ->
unless match = expression.match(proxyMethodExpressionPattern)
throw new Error "can't parse @proxyMethod expression: #{expression}"
args = name: match[4]
if match[2]?
args.toMethod = match[1]
else
args.toProperty = match[1]
if match[3]?
args.optional = true
args
proxyMethodExpressionPattern = ///
^
(.+?)
(\(\))?
(\?)?
\.
(.+?)
$
///
@garbles

This comment has been minimized.

Show comment
Hide comment
@garbles

garbles Mar 5, 2015

Been looking for something like this. Thanks for the share!

garbles commented Mar 5, 2015

Been looking for something like this. Thanks for the share!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment