Question

Assuming the presence of Harmony Proxies in the underlying Javascript engine, how could one construct a CoffeeScript superclass such that extending it would allow a class to define a noSuchMethod method (or methodMessing)?

That method would be called with a name and an argument list if the class (or its superclasses) does not have the method requested.

Was it helpful?

Solution

Nice Question! =D

(Note: i've only tested this in Firefox, as it seems is the only browser that supports Harmony proxies.)

This seems to work for missing properties:

class DynamicObject

  propertyMissingHandler =
    get: (target, name) ->
      if name of target
        target[name] 
      else
        target.propertyMissing name

  constructor: ->
    return new Proxy @, propertyMissingHandler

  # By default return undefined like a normal JS object.
  propertyMissing: -> undefined

class Repeater extends DynamicObject
  exited: no
  propertyMissing: (name) ->
    if @exited then "#{name.toUpperCase()}!" else name

r = new Repeater
console.log r.hi     # -> hi
console.log r.exited # -> false. Doesn't print "exited" ;)
r.exited = yes
console.log r.omg    # -> OMG!

Now, it works, but it has a small big caveat: it relies on an "other typed" constructor. That is, the constructor of DynamicObject returns something else than the DynamicObject instance (it returns the proxy that wraps the instance). Other typed constructors have subtle and not-so-subtle problems and they are not a very loved feature in the CoffeeScript community.

For example, the above works (in CoffeeScript 1.4), but only because the generated constructor for Repeater returns the result of calling the super constructor (and therefore returns the proxy object). If Repeater would have a different constructor, it wouldn't work:

class Repeater extends DynamicObject
  # Innocent looking constructor.
  constructor: (exited = no) ->
    @exited = exited
  propertyMissing: (name) ->
    if @exited then "#{name.toUpperCase()}!" else name

console.log (new Repeater yes).hello # -> undefined :(

You have to explicitly return the result of calling the super constructor for it to work:

  constructor: (exited = no) ->
    @exited = exited
    return super

So, as other typed constructors are kinda confusing/broken, i'd suggest avoiding them and using a class method to instantiate these objects instead of new:

class DynamicObject

  propertyMissingHandler =
    get: (target, name) ->
      if name of target
        target[name] 
      else
        target.propertyMissing name

  # Use create instead of 'new'.
  @create = (args...) ->
    instance = new @ args...
    new Proxy instance, propertyMissingHandler

  # By default return undefined like a normal JS object.
  propertyMissing: -> undefined

class Repeater extends DynamicObject
  constructor: (exited = no) ->
    @exited = exited
    # No need to worry about 'return'
  propertyMissing: (name) ->
    if @exited then "#{name.toUpperCase()}!" else name

console.log (Repeater.create yes).hello # -> HELLO!

Now, for missing methods, in order to have the same interface as requested in the question, we can do something similar in the proxy handler, but instead of directly calling a special method (propertyMissing) on the target when it has no property with that name, it returns a function, that in turn calls the special method (methodMissing):

class DynamicObject2

  methodMissingHandler =
    get: (target, name) ->
      return target[name] if name of target
      (args...) ->
        target.methodMissing name, args

  # Use this instead of 'new'.
  @create = (args...) ->
    instance = new @ args...
    new Proxy instance, methodMissingHandler 

  # By default behave somewhat similar to normal missing method calls.
  methodMissing: (name) -> throw new TypeError "#{name} is not a function"

class CommandLine extends DynamicObject2
  cd: (path) ->
    # Usually 'cd' is not a program on its own.
    console.log "Changing path to #{path}" # TODO implement me
  methodMissing: (name, args) ->
    command = "#{name} #{args.join ' '}"
    console.log "Executing command '#{command}'" 

cl = CommandLine.create()
cl.cd '/home/bob/coffee-example'  # -> Changing path to /home/bob/coffee-example
cl.coffee '-wc', 'example.coffee' # -> Executing command 'coffee -wc example.coffee'
cl.rm '-rf', '*.js'               # -> Executing command 'rm -rf *.js'

Unfortunately, i couldn't find a way to distinguish property accesses from method calls in the proxy handler so that DynamicObject could be more intelligent and call propertyMissing or methodMissing accordingly (it makes sense though, as a method call is simply a property access followed by a function call).

If i had to choose and make DynamicObject as flexible as possible, i'd go with the propertyMissing implementation, as subclasses can choose how they want to implement propertyMissing and treat that missing property as a method or not. The CommandLine example from above implemented in terms of propertyMissing would be:

class CommandLine extends DynamicObject
  cd: (path) ->
    # Usually 'cd' is not a program on its own.
    console.log "Changing path to #{path}" # TODO implement me
  propertyMissing: (name) ->
    (args...) ->
      command = "#{name} #{args.join ' '}"
      console.log "Executing command '#{command}'" 

And with that, we can now mix Repeaters and CommandLines that inherit from the same base class (how useful! =P):

cl = CommandLine.create()
r = Repeater.create yes
cl.echo r['hello proxies'] # -> Executing command 'echo HELLO PROXIES!'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top