module Treeify::ClassMethods

Public Instance Methods

appropriate_column_listing(columns = columns_joined) click to toggle source

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

# File lib/treeify.rb, line 57
def appropriate_column_listing(columns = columns_joined)
  has_config_defined_cols? == true ? ", #{columns}" : ""
end
columns_joined(char=",") click to toggle source
# File lib/treeify.rb, line 34
def columns_joined(char=",")
  self.cols ||= []
  self.cols.join(char)
end
columns_with_table_name() click to toggle source
# 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?() click to toggle source
# 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 = {}) click to toggle source
# File lib/treeify.rb, line 30
def tree_config(hash = {})
  self.cols = !hash[:cols].nil? == true ? hash[:cols] : []
end
tree_sql(instance) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# File lib/treeify.rb, line 87
def tree_sql_for_ancestors(instance)
  "#{tree_sql(instance)}
  SELECT * FROM cte 
  WHERE cte.id != #{instance.id}"
end