Created
June 7, 2012 08:00
-
-
Save shaunxcode/2887304 to your computer and use it in GitHub Desktop.
keyword dispatch/doesNotUnderstand in coffeescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 = Person.new() | |
console.log guy | |
guy | |
say: 'hello' | |
to: 'walter' | |
guy | |
doSomething: 'crazy' | |
with: 'stuff you do not comprehend' | |
guy | |
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