Module: Treeify::ClassMethods

Defined in:
lib/treeify.rb

Instance Method Summary collapse

Instance Method Details

#appropriate_column_listing(columns = columns_joined) ⇒ Object

sort of hacky, but check to see if we have any columns defined in the config if we do, return the string of columns, formatted appropriately otherwise, just return an empty string



57
58
59
# File 'lib/treeify.rb', line 57

def appropriate_column_listing(columns = columns_joined)
  has_config_defined_cols? == true ? ", #{columns}" : ""
end

#columns_joined(char = ",") ⇒ Object



34
35
36
37
# File 'lib/treeify.rb', line 34

def columns_joined(char=",")
  self.cols ||= []
  self.cols.join(char)
end

#columns_with_table_nameObject



39
40
41
42
43
44
# File 'lib/treeify.rb', line 39

def columns_with_table_name
  self.cols ||= []
  self.cols.map{|c| 
    c = "#{table_name}.#{c}" 
  }.join(",")
end

#has_config_defined_cols?Boolean

Returns:

  • (Boolean)


46
47
48
49
50
51
52
# File 'lib/treeify.rb', line 46

def has_config_defined_cols?
  #return true if self.respond_to?("cols") && !self.cols.nil? 
  if self.respond_to?("cols")
    return !self.cols.empty? if !self.cols.nil?
  end
  false
end

#tree_config(hash = {}) ⇒ Object



30
31
32
# File 'lib/treeify.rb', line 30

def tree_config(hash = {})
  self.cols = !hash[:cols].nil? == true ? hash[:cols] : []
end

#tree_sql(instance) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/treeify.rb', line 61

def tree_sql(instance)
  cte_params = has_config_defined_cols? ? "id, parent_id, path, #{columns_joined}" : "id, parent_id, path"

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

     UNION ALL

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

#tree_sql_for(instance) ⇒ Object



81
82
83
84
85
# File 'lib/treeify.rb', line 81

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

#tree_sql_for_ancestors(instance) ⇒ Object



87
88
89
90
91
# File 'lib/treeify.rb', line 87

def tree_sql_for_ancestors(instance)
  "#{tree_sql(instance)}
  SELECT * FROM cte 
  WHERE cte.id != #{instance.id}"
end