Skip to content

A platform for community discussion. Free, open, simple.

DEV: Introduce an `array` type for Chat contracts (#22278)

Loïc Guitaut885ab9a01554
diff --git a/plugins/chat/lib/chat/types/array.rb b/plugins/chat/lib/chat/types/array.rb
new file mode 100644
index 00000000000..2c4672ff1b5
--- /dev/null
+++ b/plugins/chat/lib/chat/types/array.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module Chat
+ module Types
+ class Array < ActiveModel::Type::Value
+ def serializable?(_)
+ false
+ end
+
+ def cast_value(value)
+ case value
+ when String
+ value.split(",")
+ else
+ ::Array.wrap(value)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 9f797d04800..2f0e17d373e 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -496,6 +496,8 @@ after_initialize do
)
register_bookmarkable(Chat::MessageBookmarkable)
+
+ ActiveModel::Type.register(:array, Chat::Types::Array)
end
if Rails.env == "test"
diff --git a/plugins/chat/spec/lib/chat/types/array_spec.rb b/plugins/chat/spec/lib/chat/types/array_spec.rb
new file mode 100644
index 00000000000..c6e843d4a18
--- /dev/null
+++ b/plugins/chat/spec/lib/chat/types/array_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Chat::Types::Array do
+ subject(:type) { described_class.new }
+
+ describe "#cast" do
+ subject(:casted_value) { type.cast(value) }
+
+ context "when 'value' is a string" do
+ let(:value) { "first,second,third" }
+
+ it "splits it" do
+ expect(casted_value).to eq(%w[first second third])
+ end
+ end
+
+ context "when 'value' is an array" do
+ let(:value) { %w[existing array] }
+
+ it "returns it" do
+ expect(casted_value).to eq(value)
+ end
+ end
+
+ context "when 'value' is something else" do
+ let(:value) { Time.current }
+
+ it "wraps it in a new array" do
+ expect(casted_value).to eq([value])
+ end
+ end
+ end
+end