Skip to content

Commit

Permalink
Ensure that image_kind attribute is assigned first
Browse files Browse the repository at this point in the history
... and test the other methods in the mixin
  • Loading branch information
richardTowers committed Nov 6, 2024
1 parent d48da72 commit fa41313
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
14 changes: 13 additions & 1 deletion app/models/concerns/image_kind.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions test/unit/app/models/concerns/image_kind_test.rb
Original file line number Diff line number Diff line change
@@ -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")

Check failure on line 27 in test/unit/app/models/concerns/image_kind_test.rb

View workflow job for this annotation

GitHub Actions / Lint Ruby / Run RuboCop

Layout/SpaceInsideParens: Space inside parentheses detected. (https://rubystyle.guide#spaces-braces)
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

0 comments on commit fa41313

Please sign in to comment.