Module: ClosureTree::NumericDeterministicOrdering::ClassMethods

Defined in:
lib/closure_tree/numeric_deterministic_ordering.rb

Instance Method Summary collapse

Instance Method Details

#roots_and_descendants_preorderedObject


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/closure_tree/numeric_deterministic_ordering.rb', line 52

def roots_and_descendants_preordered
  h = _ct.connection.select_one(<<-SQL.strip_heredoc)
    SELECT
      count(*) as total_descendants,
      max(generations) as max_depth
    FROM #{_ct.quoted_hierarchy_table_name}
  SQL
  join_sql = <<-SQL.strip_heredoc
    JOIN #{_ct.quoted_hierarchy_table_name} anc_hier
      ON anc_hier.descendant_id = #{_ct.quoted_table_name}.#{_ct.quoted_id_column_name}
    JOIN #{_ct.quoted_table_name} anc
      ON anc.#{_ct.quoted_id_column_name} = anc_hier.ancestor_id
    JOIN (
      SELECT descendant_id, max(generations) AS max_depth
      FROM #{_ct.quoted_hierarchy_table_name}
      GROUP BY 1
    ) AS depths ON depths.descendant_id = anc.#{_ct.quoted_id_column_name}
  SQL
  node_score = "(1 + anc.#{_ct.quoted_order_column(false)}) * " +
    "power(#{h['total_descendants']}, #{h['max_depth'].to_i + 1} - depths.max_depth)"
  order_by = "sum(#{node_score})"
  joins(join_sql).group("#{_ct.quoted_table_name}.#{_ct.quoted_id_column_name}").reorder(order_by)
end