Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Resolves #35] update cache key to use a string or an array #36

Merged
merged 1 commit into from
Apr 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions lib/apartment/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@ module Model
extend ActiveSupport::Concern

module ClassMethods
# NOTE: key is actually an array of keys. E.g. If we run the following
# query: `Setting.find_by(key: 'something', value: 'amazing')` key will
# have an array of symbols: `[:key, :something]`
# NOTE: key can either be an array of symbols or a single value.
# E.g. If we run the following query:
# `Setting.find_by(key: 'something', value: 'amazing')` key will have an array of symbols: `[:key, :something]`
# while if we run:
# `Setting.find(10)` key will have the value 'id'
def cached_find_by_statement(key, &block)
# Modifying the cache key to have a reference to the current tenant,
# so the cached statement is referring only to the tenant in which we've
# executed this
cache_key = [Apartment::Tenant.current] + key
cache_key = if key.is_a? String
"#{Apartment::Tenant.current}_#{key}"
else
[Apartment::Tenant.current] + key
end
cache = @find_by_statement_cache[connection.prepared_statements]
cache.compute_if_absent(cache_key) { ActiveRecord::StatementCache.create(connection, &block) }
end
Expand Down