From f11f4feeec5f98320f6fd68bed12b63d323ce851 Mon Sep 17 00:00:00 2001 From: Kota Shiratsuka Date: Wed, 27 Nov 2024 10:51:19 +0900 Subject: [PATCH 2/2] Calling MiniMagick every time is slow, so I'm going to --- app/helpers/application_helper.rb | 46 ++++++++++++++++++++----------- config/environments/production.rb | 3 ++ 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 62d29183d..5b9576ee6 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1007,25 +1007,39 @@ module ApplicationHelper title_and_alt = other_attrs.scan(title_and_alt_re).to_h other_attrs.gsub!(title_and_alt_re, '') - # Process dimensions and scaling - width, height = nil, nil - image = MiniMagick::Image.open(found.diskfile) - width, height = image.width, image.height - - # Adjust dimensions for @2x, @3x, etc. - if filename =~ /@(\d+)x\./ - scale_factor = $1.to_i - width /= scale_factor - height /= scale_factor - end + # Get cache store configuration + config = Rails.application.config.redmine_image_cache_store rescue :memory_store + cache_store = ActiveSupport::Cache.lookup_store(config) + + # Use digest from the database as cache key + cache_key = "image_dimensions:#{found.digest}" + + # Cache dimensions and retrieve from Redis or memory store + dimensions = cache_store.fetch(cache_key) do + # Process dimensions and scaling + image = MiniMagick::Image.open(found.diskfile) + width, height = image.width, image.height + + # Adjust dimensions for @2x, @3x, etc. + if filename =~ /@(\d+)x\./ + scale_factor = $1.to_i + width /= scale_factor + height /= scale_factor + end - # Resize if width exceeds 1000px while maintaining aspect ratio - if width > 1000 - scale = 800.0 / width - width = 800 - height = (height * scale).round + # Resize if width exceeds 1000px while maintaining aspect ratio + if width > 1000 + scale = 800.0 / width + width = 800 + height = (height * scale).round + end + + { width: width, height: height } end + width = dimensions[:width] + height = dimensions[:height] + # Add width and height to the img tag only if style attribute is absent dimension_attrs = (!has_style && width && height) ? " width=\"#{width}\" height=\"#{height}\"" : "" diff --git a/config/environments/production.rb b/config/environments/production.rb index 0d76abfff..66dc4b5cd 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -42,6 +42,9 @@ Rails.application.configure do # Use a different cache store in production. # config.cache_store = :mem_cache_store + # Using Redis Store + config.redmine_image_cache_store = :redis_cache_store, { path: '/var/run/valkey/valkey.sock' } + # Send deprecation notices to registered listeners. config.active_support.deprecation = :log -- 2.47.1