Skip to content

Commit

Permalink
Make #visit method work for null and undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
maxbrunsfeld committed Dec 27, 2012
1 parent cbebdaf commit 78474bc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
24 changes: 16 additions & 8 deletions lib/core/util/visitor.coffee
@@ -1,16 +1,24 @@
Monarch.Util.Visitor =
visit: (object, args...) ->
throw new Error("Cannot visit #{object}") unless object
if object.acceptVisitor?
object.acceptVisitor(this, args...)
if object?.acceptVisitor?
object.acceptVisitor(this, args)
else
name = object.constructor.name
method = this['visit_' + name]
throw new Error("Cannot visit #{name}") unless method
method.apply(this, arguments)
visitPrimitive.apply(this, arguments)

for moduleName in ["Expressions", "Relations"]
_.each Monarch[moduleName], (klass, klassName) ->
methodName = "visit_#{moduleName}_#{klassName}"
klass.prototype.acceptVisitor = (visitor, args...) ->
klass.prototype.acceptVisitor = (visitor, args) ->
visitor[methodName](this, args...)

visitPrimitive = (object) ->
name = visiteeName(object)
method = this['visit_' + name]
throw new Error("Cannot visit #{name}") unless method
method.apply(this, arguments)

visiteeName = (object) ->
switch object
when null then "null"
when undefined then "undefined"
else object.constructor.name
11 changes: 9 additions & 2 deletions spec/server/util/visitor_spec.coffee
Expand Up @@ -10,6 +10,8 @@ describe "Visitor", ->
SomeVisitor =
name: "Joe-Visitor"
visit: Monarch.Util.Visitor.visit,
visit_null: (obj, arg) ->
"#{@name} visited null with #{arg}"
visit_SomeModule_AcceptingClass: (obj, arg) ->
"#{@name} visited accepting class with #{arg}"
visit_NonAcceptingClass: (obj, arg) ->
Expand All @@ -33,8 +35,13 @@ describe "Visitor", ->
SomeVisitor.visit(new OtherClass)
).toThrow(new Error("Cannot visit OtherClass"))

describe "when the visitee is null", ->
it "calls the visit_Null method", ->
expect(SomeVisitor.visit(null, 2)).toBe(
'Joe-Visitor visited null with 2')

describe "when no visitee is passed", ->
it "throws an exception if no object is passed", ->
expect(-> SomeVisitor.visit(undefined)).toThrow(new Error("Cannot visit undefined"))
expect(-> SomeVisitor.visit(null)).toThrow(new Error("Cannot visit null"))
expect(-> SomeVisitor.visit(undefined)).toThrow(
new Error("Cannot visit undefined"))

0 comments on commit 78474bc

Please sign in to comment.