module ClosureTree::Finders

Public Instance Methods

find_all_by_generation(generation_level) click to toggle source
# File lib/closure_tree/finders.rb, line 36
    def find_all_by_generation(generation_level)
      s = _ct.base_class.joins(<<-SQL.squish)
        INNER JOIN (
          SELECT descendant_id
          FROM #{_ct.quoted_hierarchy_table_name}
          WHERE ancestor_id = #{_ct.quote(self.id)}
          GROUP BY descendant_id
          HAVING MAX(#{_ct.quoted_hierarchy_table_name}.generations) = #{generation_level.to_i}
        ) #{ _ct.t_alias_keyword } descendants ON (#{_ct.quoted_table_name}.#{_ct.base_class.primary_key} = descendants.descendant_id)
      SQL
      _ct.scope_with_order(s)
    end
find_by_path(path, attributes = {}) click to toggle source

Find a descendant node whose ancestry_path will be “`self.ancestry_path + path“`

# File lib/closure_tree/finders.rb, line 6
def find_by_path(path, attributes = {})
  return self if path.empty?
  self.class.find_by_path(path, attributes, id)
end
find_or_create_by_path(path, attributes = {}) click to toggle source

Find or create a descendant node whose ancestry_path will be “`self.ancestry_path + path“`

# File lib/closure_tree/finders.rb, line 12
def find_or_create_by_path(path, attributes = {})
  subpath = _ct.build_ancestry_attr_path(path, attributes)
  return self if subpath.empty?

  found = find_by_path(subpath, attributes)
  return found if found

  attrs = subpath.shift
  _ct.with_advisory_lock do
    # shenanigans because children.create is bound to the superclass
    # (in the case of polymorphism):
    child = self.children.where(attrs).first || begin
      # Support STI creation by using base_class:
      _ct.create(self.class, attrs).tap do |ea|
        # We know that there isn't a cycle, because we just created it, and
        # cycle detection is expensive when the node is deep.
        ea._ct_skip_cycle_detection!
        self.children << ea
      end
    end
    child.find_or_create_by_path(subpath, attributes)
  end
end
without_self(scope) click to toggle source
# File lib/closure_tree/finders.rb, line 49
def without_self(scope)
  scope.without_instance(self)
end