Skip to content

Commit

Permalink
extract ancestry_depth_sql to module methods
Browse files Browse the repository at this point in the history
want to call these from tests
kbrock committed Oct 22, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 8a4e7c0 commit 7176d19
Showing 3 changed files with 17 additions and 12 deletions.
13 changes: 7 additions & 6 deletions lib/ancestry/materialized_path.rb
Original file line number Diff line number Diff line change
@@ -101,12 +101,7 @@ def child_ancestry_sql
end

def ancestry_depth_sql
@ancestry_depth_sql ||=
begin
tmp = %{(LENGTH(#{table_name}.#{ancestry_column}) - LENGTH(REPLACE(#{table_name}.#{ancestry_column},'#{ancestry_delimiter}','')))}
tmp = tmp + "/#{ancestry_delimiter.size}" if ancestry_delimiter.size > 1
"(CASE WHEN #{table_name}.#{ancestry_column} IS NULL THEN 0 ELSE 1 + #{tmp} END)"
end
@ancestry_depth_sql ||= MaterializedPath.construct_depth_sql(table_name, ancestry_column, ancestry_delimiter)
end

def generate_ancestry(ancestor_ids)
@@ -135,6 +130,12 @@ def concat(*args)
end
end

def self.construct_depth_sql(table_name, ancestry_column, ancestry_delimiter)
tmp = %{(LENGTH(#{table_name}.#{ancestry_column}) - LENGTH(REPLACE(#{table_name}.#{ancestry_column},'#{ancestry_delimiter}','')))}
tmp = tmp + "/#{ancestry_delimiter.size}" if ancestry_delimiter.size > 1
"(CASE WHEN #{table_name}.#{ancestry_column} IS NULL THEN 0 ELSE 1 + #{tmp} END)"
end

private

def ancestry_validation_options(ancestry_primary_key_format)
14 changes: 8 additions & 6 deletions lib/ancestry/materialized_path2.rb
Original file line number Diff line number Diff line change
@@ -33,12 +33,7 @@ def child_ancestry_sql
end

def ancestry_depth_sql
@ancestry_depth_sql ||=
begin
tmp = %{(LENGTH(#{table_name}.#{ancestry_column}) - LENGTH(REPLACE(#{table_name}.#{ancestry_column},'#{ancestry_delimiter}','')))}
tmp = tmp + "/#{ancestry_delimiter.size}" if ancestry_delimiter.size > 1
"(#{tmp} -1)"
end
@ancestry_depth_sql ||= MaterializedPath2.construct_depth_sql(table_name, ancestry_column, ancestry_delimiter)
end

def generate_ancestry(ancestor_ids)
@@ -49,6 +44,13 @@ def generate_ancestry(ancestor_ids)
end
end

# module method
def self.construct_depth_sql(table_name, ancestry_column, ancestry_delimiter)
tmp = %{(LENGTH(#{table_name}.#{ancestry_column}) - LENGTH(REPLACE(#{table_name}.#{ancestry_column},'#{ancestry_delimiter}','')))}
tmp = tmp + "/#{ancestry_delimiter.size}" if ancestry_delimiter.size > 1
"(#{tmp} -1)"
end

private

def ancestry_nil_allowed?
2 changes: 2 additions & 0 deletions test/concerns/db_test.rb
Original file line number Diff line number Diff line change
@@ -3,6 +3,8 @@
class DbTest < ActiveSupport::TestCase
def test_does_not_load_database
c = Class.new(ActiveRecord::Base) do
self.table_name = "table"

def self.connection
raise "Oh No - tried to connect to database"
end

0 comments on commit 7176d19

Please sign in to comment.