about summary refs log tree commit diff
path: root/app/controllers/application_controller.rb
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2016-11-29 15:49:39 +0100
committerEugen Rochko <eugen@zeonfederated.com>2016-11-29 15:49:39 +0100
commit7e90772c92fd121dfe0f1eb788fb09eb3df4cbc8 (patch)
tree12965c80362a71d8f0d436c815f4fb4aa2d25b85 /app/controllers/application_controller.rb
parent93a90cd9c364680cfcc4c1d1ada13efed233e5bd (diff)
Unify collection caching code
Diffstat (limited to 'app/controllers/application_controller.rb')
-rw-r--r--app/controllers/application_controller.rb19
1 files changed, 19 insertions, 0 deletions
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index b03a2cdea..ba0098c71 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -52,4 +52,23 @@ class ApplicationController < ActionController::Base
   def current_account
     @current_account ||= current_user.try(:account)
   end
+
+  def cache_collection(raw, klass)
+    uncached_ids           = []
+    cached_keys_with_value = Rails.cache.read_multi(*raw.map(&:cache_key))
+
+    raw.each do |item|
+      uncached_ids << item.id unless cached_keys_with_value.key?(item.cache_key)
+    end
+
+    unless uncached_ids.empty?
+      uncached = klass.where(id: uncached_ids).with_includes.map { |item| [item.id, item] }.to_h
+
+      uncached.values.each do |item|
+        Rails.cache.write(item.cache_key, item)
+      end
+    end
+
+    raw.map { |item| cached_keys_with_value[item.cache_key] || uncached[item.id] }.compact
+  end
 end