Skip to content

Commit

Permalink
Cache the is_sharded? status of the model
Browse files Browse the repository at this point in the history
Sets self.sharded depending on the superclass, if it is not otherwise
set.
  • Loading branch information
KJ Tsanaktsidis committed Apr 5, 2023
1 parent a1d4f85 commit f6cd9ce
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions lib/active_record_shards/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down

0 comments on commit f6cd9ce

Please sign in to comment.