Module: ClosureTree::Finders
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/closure_tree/finders.rb
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
- #find_all_by_generation(generation_level) ⇒ Object
-
#find_by_path(path, attributes = {}) ⇒ Object
Find a descendant node whose
ancestry_path
will be “‘self.ancestry_path + path“`. -
#find_or_create_by_path(path, attributes = {}) ⇒ Object
Find or create a descendant node whose
ancestry_path
will be “‘self.ancestry_path + path“`. - #without_self(scope) ⇒ Object
Instance Method Details
#find_all_by_generation(generation_level) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/closure_tree/finders.rb', line 36 def find_all_by_generation(generation_level) s = _ct.base_class.joins(<<-SQL.strip_heredoc) 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} ) AS 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 = {}) ⇒ Object
Find a descendant node whose ancestry_path
will be “‘self.ancestry_path + path“`
6 7 8 9 |
# 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 = {}) ⇒ Object
Find or create a descendant node whose ancestry_path
will be “‘self.ancestry_path + path“`
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# 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) ⇒ Object
49 50 51 |
# File 'lib/closure_tree/finders.rb', line 49 def without_self(scope) scope.without_instance(self) end |