From d3ee2911fa7adcc2740fc93eece011fb6a920d10 Mon Sep 17 00:00:00 2001 From: Richard Towers Date: Tue, 5 Nov 2024 13:35:36 +0000 Subject: [PATCH] Ensure that image_kind attribute is assigned first ... and test the other methods in the mixin --- app/models/concerns/image_kind.rb | 14 +++++++- .../app/models/concerns/image_kind_test.rb | 34 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 test/unit/app/models/concerns/image_kind_test.rb diff --git a/app/models/concerns/image_kind.rb b/app/models/concerns/image_kind.rb index dda90ffab2a..1a482b59e05 100644 --- a/app/models/concerns/image_kind.rb +++ b/app/models/concerns/image_kind.rb @@ -2,8 +2,20 @@ module ImageKind extend ActiveSupport::Concern included do + def assign_attributes(attributes) + # It's important that the image_kind attribute is assigned first, as it is intended to be used by + # carrierwave uploaders when they are mounted to work out which image versions to use. + image_kind = attributes.delete(:image_kind) + ordered_attributes = if image_kind.present? + { image_kind:, **attributes } + else + attributes + end + super ordered_attributes + end + def image_kind - attributes.fetch(:image_kind, "default") + attributes.fetch("image_kind", "default") end def image_kind_config diff --git a/test/unit/app/models/concerns/image_kind_test.rb b/test/unit/app/models/concerns/image_kind_test.rb new file mode 100644 index 00000000000..235f59c4ed9 --- /dev/null +++ b/test/unit/app/models/concerns/image_kind_test.rb @@ -0,0 +1,34 @@ +require "test_helper" + +class ImageKindTest < ActiveSupport::TestCase + setup do + @test_instance = ( + Class.new do + include ActiveModel::Model + include ActiveModel::Attributes + include ActiveModel::AttributeAssignment + + include ImageKind + + attr_reader :assigned_attributes + + def assign_attributes(attributes) + @assigned_attributes = attributes + end + end + ).new + end + + test "adds an image_kind method with a default" do + assert_equal "default", @test_instance.image_kind + end + + test "reorders attributes so image_kind comes first" do + @test_instance.assign_attributes(file: "some file", image_kind: "some image kind") + assert_equal({ image_kind: "some image kind", file: "some file" }, @test_instance.assigned_attributes) + end + + test "loads image_kind_config" do + assert_instance_of Whitehall::ImageKind, @test_instance.image_kind_config + end +end