Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add option for creating the representative node if lookup fails

Supports the common 'get or create' use case if `options.create` is true
  • Loading branch information...
commit 4d8a278256fe472c639754d0d9f76cc9e418cb1c 1 parent ceedd3e
@bruth bruth authored
Showing with 21 additions and 10 deletions.
  1. +21 −10 coffee/cilantro/models/context.coffee
View
31 coffee/cilantro/models/context.coffee
@@ -51,9 +51,11 @@ define [
isTyped: ->
@attributes.field? or @attributes.concept?
- fetch: (query, options) ->
+ fetch: (query, options={}) ->
if queryAttrs(@, query, options)
return @
+ if options.create isnt false
+ return new @constructor query
# Branch-type node that acts as a container for other nodes. The `type`
@@ -89,18 +91,27 @@ define [
return message
return
- fetch: (query, options) ->
- if (node = super) then return node
+ fetch: (query, options={}) ->
+ # Set false to prevent shadowing the children below
+ create = options.create
+ options.create = false
+
+ if (node = super(query, options))
+ return node
children = @get('children')
+
+ # Recurse on each child node for a match, converting raw
+ # attributes into nodes as needed
for child, i in children
- if queryAttrs(child, query, options)
- # If this a match, convert the child into an instance
- # for downstream use.
- if not (child instanceof ContextNodeModel)
- child = children[i] = getContextNodeModel(child, options)
- return child
- return
+ if not (child instanceof ContextNodeModel)
+ child = children[i] = getContextNodeModel(child, options)
+ if (node = child.fetch(query, options))
+ return node
+
+ if create isnt false
+ @add(node = new @constructor query)
+ return node
# If this is a deep save, recursively save children prior to
# creating a copy to publicAttributes.
Please sign in to comment.
Something went wrong with that request. Please try again.