Skip to content

Instantly share code, notes, and snippets.

@jszmajda
Created January 5, 2010 18:21
Show Gist options
  • Save jszmajda/269576 to your computer and use it in GitHub Desktop.
Save jszmajda/269576 to your computer and use it in GitHub Desktop.
module MongoMapper
module Associations
class InArrayProxy < Collection
def set_parent(parent, options={})
self.each do |k|
k.set_parent(parent)
if (!options.has_key?(:recursive) or options[:recursive] == true) and k.send( reflection.name ).size > 0
k.send( reflection.name ).set_parent(k, options)
end
end
end
end
end
end
class Node
include MongoMapper::Document
key :ord, Integer, :index => true
key :node_ids, Array, :index => true
many :nodes, :in => :node_ids, :order => 'ord'
def parent
@parent
end
def siblings(node_id = nil)
return [] if !parent
if node_id
node_id = Mongo::ObjectID.from_string(node_id) if node_id.is_a? String
parent.nodes.each {|n| return n if n.id == node_id }
else
parent.nodes.reject{ |n| n == self }
end
end
protected
def set_parent(parent_node)
@parent = parent_node
end
end
n = Node.find(:first)
# sets 'n' as the @parent var on each child node, so the siblings method works properly
n.nodes.set_parent(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment