Skip to content

Instantly share code, notes, and snippets.

@mohnish
Forked from sstephenson/proxyMethod.coffee
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save mohnish/fab6077b53f6789a28fe to your computer and use it in GitHub Desktop.

Select an option

Save mohnish/fab6077b53f6789a28fe 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 = ///
^
(.+?)
(\(\))?
(\?)?
\.
(.+?)
$
///
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment