Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
keyword dispatch/doesNotUnderstand in coffeescript
#this is absolutely just for fun
keyWordDispatcher = (obj, msg) ->
selectorName = ""
args = []
for k, v of msg
selectorName += k + "_"
args.push v
if obj[selectorName]?
return obj[selectorName].apply obj, args
if obj.doesNotUnderstand?
return obj.doesNotUnderstand selectorName, args
throw new Exception "can not dispatch #{selectorName}"
keyWordDispatcher.make = (obj) -> (msg) -> keyWordDispatcher obj, msg
class Person
@new: -> keyWordDispatcher.make new @
say_to_: (aPhrase, aPerson) ->
console.log "called for #{aPhrase} and #{aPerson}"
doesNotUnderstand: (selector, args) ->
console.log "don't grok #{selector}.. do magic things. args:", args
from_to_do_: (start, end, block) ->
block i for i in [start..end]
guy =
console.log guy
say: 'hello'
to: 'walter'
doSomething: 'crazy'
with: 'stuff you do not comprehend'
from: 1
to: 10
do: (i) ->
console.log i * 2
num = keyWordDispatcher.make
str = keyWordDispatcher.make
Number::to_do_ = (limit, block) -> block i for i in [@..limit]
String::charAt_ = (i) -> @charAt i
(num 1)
to: 6
do: (i) -> console.log " ha ha #{i}"
(str "cat") charAt: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment