PERF: automatic upload size calculation not persisted

PERF: automatic upload size calculation not persisted

Previously if upload had missing width and height we would calculate
on first use BUT we (me) forgot to save this to the database

This was particularly bad on home page cause category images (when old)
miss dimensions.

diff --git a/app/models/upload.rb b/app/models/upload.rb
index a14b71b..a90eb4c 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -126,8 +126,19 @@ class Upload < ActiveRecord::Base
       end
 
     begin
-      self.width, self.height = size = FastImage.new(path, raise_on_failure: true).size
-      self.thumbnail_width, self.thumbnail_height = ImageSizer.resize(*size)
+      w, h = FastImage.new(path, raise_on_failure: true).size
+
+      self.width = w || 0
+      self.height = h || 0
+
+      self.thumbnail_width, self.thumbnail_height = ImageSizer.resize(w, h)
+
+      self.update_columns(
+        width: width,
+        height: height,
+        thumbnail_width: thumbnail_width,
+        thumbnail_height: thumbnail_height
+      )
     rescue => e
       Discourse.warn_exception(e, message: "Error getting image dimensions")
     end
diff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rb
index aba1b21..1fe964d 100644
--- a/spec/models/upload_spec.rb
+++ b/spec/models/upload_spec.rb
@@ -55,6 +55,9 @@ describe Upload do
     expect(upload.width).to eq(64250)
     expect(upload.height).to eq(64250)
 
+    upload.reload
+    expect(upload.read_attribute(:width)).to eq(64250)
+
     upload.update_columns(width: nil, height: nil, thumbnail_width: nil, thumbnail_height: nil)
 
     expect(upload.thumbnail_width).to eq(500)

GitHub
sha: 303a535d

1 Like