@@ -2,57 +2,16 @@ module ClosureTree
22 module HashTree
33 extend ActiveSupport ::Concern
44
5- def hash_tree_scope ( limit_depth = nil )
6- scope = self_and_descendants
7- if limit_depth
8- scope . where ( "#{ _ct . quoted_hierarchy_table_name } .generations <= #{ limit_depth - 1 } " )
9- else
10- scope
11- end
12- end
13-
145 def hash_tree ( options = { } )
15- self . class . build_hash_tree ( hash_tree_scope ( options [ :limit_depth ] ) )
6+ _ct . hash_tree ( self_and_descendants , options [ :limit_depth ] )
167 end
178
189 module ClassMethods
1910
2011 # There is no default depth limit. This might be crazy-big, depending
2112 # on your tree shape. Hash huge trees at your own peril!
2213 def hash_tree ( options = { } )
23- build_hash_tree ( hash_tree_scope ( options [ :limit_depth ] ) )
24- end
25-
26- def hash_tree_scope ( limit_depth = nil )
27- # Deepest generation, within limit, for each descendant
28- # NOTE: Postgres requires HAVING clauses to always contains aggregate functions (!!)
29- having_clause = limit_depth ? "HAVING MAX(generations) <= #{ limit_depth - 1 } " : ''
30- generation_depth = <<-SQL . strip_heredoc
31- INNER JOIN (
32- SELECT descendant_id, MAX(generations) as depth
33- FROM #{ _ct . quoted_hierarchy_table_name }
34- GROUP BY descendant_id
35- #{ having_clause }
36- ) AS generation_depth
37- ON #{ _ct . quoted_table_name } .#{ primary_key } = generation_depth.descendant_id
38- SQL
39- _ct . scope_with_order ( joins ( generation_depth ) , "generation_depth.depth" )
40- end
41-
42- # Builds nested hash structure using the scope returned from the passed in scope
43- def build_hash_tree ( tree_scope )
44- tree = ActiveSupport ::OrderedHash . new
45- id_to_hash = { }
46-
47- tree_scope . each do |ea |
48- h = id_to_hash [ ea . id ] = ActiveSupport ::OrderedHash . new
49- if ea . root? || tree . empty? # We're at the top of the tree.
50- tree [ ea ] = h
51- else
52- id_to_hash [ ea . _ct_parent_id ] [ ea ] = h
53- end
54- end
55- tree
14+ _ct . hash_tree ( nil , options [ :limit_depth ] )
5615 end
5716 end
5817 end
0 commit comments