diff --git a/lib/ancestry/materialized_path.rb b/lib/ancestry/materialized_path.rb index 41eb84d3..d53854af 100644 --- a/lib/ancestry/materialized_path.rb +++ b/lib/ancestry/materialized_path.rb @@ -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) diff --git a/lib/ancestry/materialized_path2.rb b/lib/ancestry/materialized_path2.rb index 47d520f8..46887852 100644 --- a/lib/ancestry/materialized_path2.rb +++ b/lib/ancestry/materialized_path2.rb @@ -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? diff --git a/test/concerns/db_test.rb b/test/concerns/db_test.rb index eb794056..fe2001c8 100644 --- a/test/concerns/db_test.rb +++ b/test/concerns/db_test.rb @@ -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