Module: Treeify::ClassMethods

Defined in:
lib/treeify.rb

Instance Method Summary collapse

Instance Method Details

#config(hash = {}) ⇒ Object



24
25
26
27
# File 'lib/treeify.rb', line 24

def config(hash = {})
  # apparently columns is a reserved word in rails
  self.cols       = hash[:cols]
end

#tree_sql(instance) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/treeify.rb', line 29

def tree_sql(instance)
  "WITH RECURSIVE cte (id, path)  AS (
     SELECT  id,
       array[id] AS path
     FROM    #{table_name}
     WHERE   id = #{instance.id}

     UNION ALL

     SELECT  #{table_name}.id,
        cte.path || #{table_name}.id
     FROM    #{table_name}
     JOIN cte ON #{table_name}.parent_id = cte.id
   )"
end

#tree_sql_for(instance) ⇒ Object



45
46
47
48
49
# File 'lib/treeify.rb', line 45

def tree_sql_for(instance)
  "#{tree_sql(instance)}
   SELECT id FROM cte
   ORDER BY path"
end

#tree_sql_for_ancestors(instance) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/treeify.rb', line 51

def tree_sql_for_ancestors(instance)
  "WITH RECURSIVE cte (id, path)  AS (
     SELECT  id,
       array[id] AS path
     FROM    #{table_name}
     WHERE   id = #{instance.id}
     
     UNION ALL

     SELECT  #{table_name}.id,
        cte.path || #{table_name}.id
     FROM    #{table_name}
     JOIN cte ON #{table_name}.parent_id = cte.id
   )
  SELECT cte.id FROM cte WHERE cte.id != #{instance.id}"
end