Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Last active August 29, 2015 14:14
Show Gist options
  • Save sstephenson/5e46cd5c9063b3f1079b to your computer and use it in GitHub Desktop.
Save sstephenson/5e46cd5c9063b3f1079b to your computer and use it in GitHub Desktop.
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
Copy link

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