Created
November 23, 2008 21:29
-
-
Save dburger/28216 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Returns hierarchical data structure rooted at this node. When converting to | |
# json make sure to remove :parent to avoid circular reference: | |
# message.full_hierarchy.to_json(:only => [:id, :subject, :children, ...]) | |
def full_hierarchy | |
the_full_set = full_set | |
ancestry = [build_node(the_full_set.shift)] | |
while !the_full_set.empty? | |
next_node = build_node(the_full_set.shift) | |
while next_node[:level] <= ancestry.last[:level] | |
ancestry.pop | |
end | |
ancestry.last[:children] << next_node | |
ancestry.last[:leaf] = false | |
next_node[:parent] = ancestry.last | |
ancestry << next_node | |
end | |
ancestry[0] | |
end | |
private | |
# active record Message to node for hierarchy | |
def build_node(message) | |
ret = {} | |
ret[:id] = message.id | |
ret[:subject] = message.subject | |
ret[:message] = message.message | |
ret[:level] = message.level | |
ret[:account_id] = message.account_id | |
ret[:author] = message.account.login | |
ret[:children] = [] | |
ret[:parent] = nil | |
ret[:leaf] = true | |
ret | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment