From adb61e48c5878833ff89c67054cea5e5d2a585b0 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Thu, 2 Apr 2020 19:09:03 +0200 Subject: [PATCH] Cache counts used in homepage for 24 hours --- app/controllers/home_controller.rb | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index f8268cf464..0a39b00d9b 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -5,12 +5,23 @@ class HomeController < BaseController def index if ContentConfig.home_show_stats - @num_distributors = Enterprise.is_distributor.activated.visible.count - @num_producers = Enterprise.is_primary_producer.activated.visible.count - @num_users = Spree::Order.complete.count('DISTINCT user_id') - @num_orders = Spree::Order.complete.count + @num_distributors = cached_count('distributors', Enterprise.is_distributor.activated.visible) + @num_producers = cached_count('producers', Enterprise.is_primary_producer.activated.visible) + @num_orders = cached_count('orders', Spree::Order.complete) + @num_users = cached_count( + 'users', Spree::Order.complete.select('DISTINCT spree_orders.user_id') + ) end end def sell; end + + private + + # Cache the value of the query count for 24 hours + def cached_count(key, query) + Rails.cache.fetch("home_stats_count_#{key}", expires_in: 1.day, race_condition_ttl: 10) do + query.count + end + end end