Module: Ltree::Hierarchy
- Defined in:
- lib/ltree_hierarchy/version.rb,
lib/ltree_hierarchy/hierarchy.rb
Defined Under Namespace
Modules: InstanceMethods
Constant Summary collapse
- VERSION =
"0.0.6"
Instance Method Summary collapse
- #at_depth(depth) ⇒ Object
- #has_ltree_hierarchy(options = {}) ⇒ Object
- #leaves ⇒ Object
- #lowest_common_ancestor_paths(paths) ⇒ Object
- #lowest_common_ancestors(paths) ⇒ Object
- #roots ⇒ Object
Instance Method Details
#at_depth(depth) ⇒ Object
32 33 34 |
# File 'lib/ltree_hierarchy/hierarchy.rb', line 32 def at_depth(depth) where(["nlevel(#{ltree_path_column}) = ?", depth]) end |
#has_ltree_hierarchy(options = {}) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/ltree_hierarchy/hierarchy.rb', line 3 def has_ltree_hierarchy( = {}) = { :fragment => :id, :parent_fragment => :parent_id, :path => :path }.merge() .assert_valid_keys(:fragment, :parent_fragment, :path) cattr_accessor :ltree_fragment_column, :ltree_parent_fragment_column, :ltree_path_column self.ltree_fragment_column = [:fragment] self.ltree_parent_fragment_column = [:parent_fragment] self.ltree_path_column = [:path] belongs_to :parent, :class_name => self.name, :foreign_key => self.ltree_parent_fragment_column validate :prevent_circular_paths, :if => :ltree_parent_fragment_changed? after_create :commit_path before_update :assign_path, :cascade_path_change, :if => :ltree_parent_fragment_changed? include InstanceMethods end |
#leaves ⇒ Object
36 37 38 39 |
# File 'lib/ltree_hierarchy/hierarchy.rb', line 36 def leaves subquery = select("DISTINCT #{ltree_parent_fragment_column}") where("#{ltree_fragment_column} NOT IN(#{subquery.to_sql})") end |
#lowest_common_ancestor_paths(paths) ⇒ Object
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/ltree_hierarchy/hierarchy.rb', line 41 def lowest_common_ancestor_paths(paths) sql = if paths.respond_to?(:to_sql) "SELECT lca(array(#{paths.to_sql}))" else return [] if paths.empty? safe_paths = paths.map { |p| "#{connection.quote(p)}::ltree" } "SELECT lca(ARRAY[#{safe_paths.join(', ')}])" end connection.select_values(sql) end |
#lowest_common_ancestors(paths) ⇒ Object
52 53 54 |
# File 'lib/ltree_hierarchy/hierarchy.rb', line 52 def lowest_common_ancestors(paths) where(ltree_path_column => lowest_common_ancestor_paths(paths)) end |
#roots ⇒ Object
28 29 30 |
# File 'lib/ltree_hierarchy/hierarchy.rb', line 28 def roots where(self.ltree_parent_fragment_column => nil) end |