From bfc99f0d4ce2556ba25b5fa5340581553cdbf1bd Mon Sep 17 00:00:00 2001 From: KJ Tsanaktsidis Date: Wed, 5 Apr 2023 15:14:02 +1000 Subject: [PATCH] Cache the is_sharded? status of the model Sets self.sharded depending on the superclass, if it is not otherwise set. --- lib/active_record_shards/model.rb | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/lib/active_record_shards/model.rb b/lib/active_record_shards/model.rb index 7d3c6581..e257035f 100644 --- a/lib/active_record_shards/model.rb +++ b/lib/active_record_shards/model.rb @@ -11,17 +11,26 @@ def not_sharded end def is_sharded? # rubocop:disable Naming/PredicateName - if self == ActiveRecord::Base - sharded != false && supports_sharding? - elsif self == base_class - if sharded.nil? - ActiveRecord::Base.is_sharded? - else - sharded != false - end - else - base_class.is_sharded? - end + # "sharded" here means self.sharded, but actually writing "self.sharded" + # doesn't work until Ruby 2.7 (and this gem currently supports 2.6) because + # the sharded attr_accessor is private. Private methods must be called without + # a receiver, but Ruby 2.7+ does allow an explicit "self" as a receiver. + return sharded unless sharded.nil? + + # Despite self.sharded not working, self.sharded= _DOES_ work. That's an exception + # to the "private methods must be called with no receiver" rule (presumably + # because it would otherwise be ambiguous with local variable assignment). + self.sharded = if self == ActiveRecord::Base + sharded != false && supports_sharding? + elsif self == base_class + if sharded.nil? + ActiveRecord::Base.is_sharded? + else + sharded != false + end + else + base_class.is_sharded? + end end def on_replica_by_default?