Skip to content

Commit aa59cf6

Browse files
committed
made normalize_collection a class method & added test for it
1 parent 45ef22c commit aa59cf6

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

lib/namespaced_env_cache.rb

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def write_collection(name, value, **opts)
8585
raise TypeError, "Can't cache more than one type of object via write_collection"
8686
end
8787

88-
data = normalize_collection(value)
88+
data = NamespacedEnvCache.normalize_collection(value)
8989
namespaced = construct_ns_key(name, include_community: include_community(opts))
9090
@underlying.write(namespaced, data, **opts)
9191
end
@@ -102,7 +102,7 @@ def read_collection(name, **opts)
102102
return nil if data.nil?
103103

104104
if data.is_a?(ActiveRecord::Relation)
105-
data = normalize_collection(data)
105+
data = NamespacedEnvCache.normalize_collection(data)
106106
end
107107

108108
type = data.slice!(0)
@@ -136,6 +136,13 @@ def fetch_collection(name, **opts, &block)
136136
end
137137
end
138138

139+
# Normalizes a given ActiveRecord collection for use with the cache
140+
# @param value [ActiveRecord::Relation] collection to normalize
141+
# @return [Array(String, *Integer)]
142+
def self.normalize_collection(value)
143+
[value[0].class.to_s, *value.map(&:id)]
144+
end
145+
139146
# We have to statically report that we support cache versioning even though this depends on the underlying class.
140147
# However, this is not really a problem since all cache stores provided by activesupport support the feature and
141148
# we only use the redis cache (by activesupport) for QPixel.
@@ -150,12 +157,5 @@ def construct_ns_key(key, include_community: true)
150157
c_id = RequestContext.community_id if include_community
151158
"#{Rails.env}://#{[c_id, key].compact.join('/')}"
152159
end
153-
154-
# Normalizes a given ActiveRecord collection for use with the cache
155-
# @param value [ActiveRecord::Relation] collection to normalize
156-
# @return [Array(String, *Integer)]
157-
def normalize_collection(value)
158-
[value[0].class.to_s, *value.map(&:id)]
159-
end
160160
end
161161
end

test/lib/namespaced_env_cache_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ class NamespacedEnvCacheTest < ActiveSupport::TestCase
4848
end
4949
end
5050

51+
test 'normalize_collection should correctly prepare collections for caching' do
52+
collection = Post.where(user: users(:standard_user))
53+
normalized = QPixel::NamespacedEnvCache.normalize_collection(collection)
54+
assert_equal Post.name, normalized.shift
55+
assert(collection.to_a.all? { |post| normalized.include?(post.id) })
56+
end
57+
5158
private
5259

5360
def new_cache_store

0 commit comments

Comments
 (0)