mceachen/closure_tree — pull request #36 by elskwid (2013-01-02 19:40:20+00:00)
Title: New scopes - for discussion

Greetings and Happy New Year!

I'd like to discuss the various things I've been poking and prodding over the last few days. I fear that I've gone a bit too far. Tampering with things I don't understand. Playing God. You know how it is.

### Highlights

By adding a couple of scope methods to the hierarchy model I've been able to clarify how different items are related and get more chained scopes which adds a nice hint of composability to it all. Just a dash.

`.depths` - Hierarchy information grouped by descendant_id, optionally limited to a depth or specific node. (options: :limit, :only, :node) Depth of a node is number of nodes to its root.
`.heights` - Hierarchy information grouped by ancestor_id, optionally limited to a height or specific node. (options: :limit, :only, :node) Height of a node is number of nodes to a leaf of that node. _Note: node height makes my brain hurt._

Big ups to Wikipedia. https://en.wikipedia.org/wiki/Tree_(data_structure)

I added a few class methods to the model itself:

`.with_depths` - gives us the model joined to the `Hierarchy.depths`
`.with_heights` - the model joined to the `Hierarchy.heights`

We can use these to drive much of the functionality needed in other methods …

`.tree` - the tree, optionally starting at a specific node
`at_depth` - limited by depth (limit or only).
`.at_height` - limited by height (limit or only).

### Deep thoughts

I have some questions on depths, namely, that there seems to be a slight difference in `Model.find_all_by_generation` and `Model#find_all_by_generation`. The former is just a blanket "gimme everything at generation N" while the latter is "gimme everything that is N away from this node". Doesn't feel the same to me.

Ordering also looks like it is ripe for the taking. By default `.order` is additive. The use of `append_order` can lead to `ORDER` having the same field listed more than once and that blew up for me in amazing ways. The append method is used in at least one association which might not be the best place for it.

### Deeper thoughts

I'll save these for my next round.

### What now?

Anyway, all tests are green and I can see some interesting possibilities in traversal and other crazy things that we get by adding this concepts of `depth` and `height` to the hierarchy model. If we can clear up what some of the other methods mean we can really kick some heads. In a code-sense of course.

Happy to discuss this over G+ Hangout or in this PR.

I don't actually expect that this gets merged as is - just needed a break point for discussion. Thanks for being so open to my contributions. I hope they have some merit outside of my head.