From f6cd9ce2bce3c18e61925099a8b7944bcdb38e8d 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 | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/lib/active_record_shards/model.rb b/lib/active_record_shards/model.rb index 7d3c6581..44cdcdcb 100644 --- a/lib/active_record_shards/model.rb +++ b/lib/active_record_shards/model.rb @@ -11,17 +11,22 @@ 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). + return sharded unless sharded.nil? + + # Despite self.sharded not working, self.sharded= _DOES_ work. + 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?