forked from benedikt/mongoid-tree
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added some macros to help setting up trees in specs
- Loading branch information
Showing
4 changed files
with
121 additions
and
57 deletions.
There are no files selected for viewing
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 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 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
require 'yaml' | ||
|
||
module Mongoid::Tree::TreeMacros | ||
|
||
def setup_tree(tree) | ||
create_tree(YAML.load(tree)) | ||
end | ||
|
||
def node(name) | ||
@nodes[name].reload | ||
end | ||
|
||
def print_tree(node, print_ids = false, depth = 0) | ||
print ' ' * depth | ||
print '- ' unless depth == 0 | ||
print node.name | ||
print " (#{node.id})" if print_ids | ||
print ':' if node.children.any? | ||
print "\n" | ||
node.children.each { |c| print_tree(c, print_ids, depth + 1) } | ||
end | ||
|
||
private | ||
|
||
def create_tree(object) | ||
case object | ||
when String: return create_node(object) | ||
when Array: object.each { |tree| create_tree(tree) } | ||
when Hash: | ||
name, children = object.first | ||
node = create_node(name) | ||
children.each { |c| node.children << create_tree(c) } | ||
return node | ||
end | ||
end | ||
|
||
def create_node(name) | ||
@nodes ||= HashWithIndifferentAccess.new | ||
@nodes[name] = Node.create(:name => name) | ||
end | ||
|
||
end | ||
|
||
RSpec.configure do |config| | ||
config.include Mongoid::Tree::TreeMacros | ||
end |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
class Node | ||
include Mongoid::Document | ||
include Mongoid::Tree | ||
|
||
field :name | ||
end | ||
|