Skip to content

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

DEV: Add `symbol` to ActiveModel attribute types (#36420)

Loïc Guitauta8b312426b7d
diff --git a/config/initializers/100-active-support-type-extensions.rb b/config/initializers/100-active-support-type-extensions.rb
index 598f0df32dd..145d1b84094 100644
--- a/config/initializers/100-active-support-type-extensions.rb
+++ b/config/initializers/100-active-support-type-extensions.rb
@@ -2,4 +2,5 @@
Rails.application.config.to_prepare do
ActiveModel::Type.register(:array, ActiveSupportTypeExtensions::Array)
+ ActiveModel::Type.register(:symbol, ActiveSupportTypeExtensions::Symbol)
end
diff --git a/lib/active_support_type_extensions/symbol.rb b/lib/active_support_type_extensions/symbol.rb
new file mode 100644
index 00000000000..2c67b3ecc04
--- /dev/null
+++ b/lib/active_support_type_extensions/symbol.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module ActiveSupportTypeExtensions
+ class Symbol < ActiveModel::Type::Value
+ def serializable?(_)
+ false
+ end
+
+ def cast_value(value)
+ case value
+ when Symbol, NilClass
+ value
+ else
+ value.to_s.presence.try(:to_sym)
+ end
+ end
+ end
+end
diff --git a/spec/lib/active_support_type_extensions/symbol_spec.rb b/spec/lib/active_support_type_extensions/symbol_spec.rb
new file mode 100644
index 00000000000..d7adf3f0c3d
--- /dev/null
+++ b/spec/lib/active_support_type_extensions/symbol_spec.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+RSpec.describe ActiveSupportTypeExtensions::Symbol do
+ subject(:type) { described_class.new }
+
+ describe "#cast" do
+ subject(:casted_value) { type.cast(value) }
+
+ context "when 'value' is a string" do
+ let(:value) { "a_symbol" }
+
+ it "converts it" do
+ expect(casted_value).to eq(:a_symbol)
+ end
+ end
+
+ context "when 'value' is a symbol" do
+ let(:value) { :a_symbol }
+
+ it "returns it" do
+ expect(casted_value).to eq(value)
+ end
+ end
+
+ context "when 'value' is nil" do
+ let(:value) { nil }
+
+ it "returns nil" do
+ expect(casted_value).to eq(value)
+ end
+ end
+
+ context "when 'value' is blank" do
+ let(:value) { "" }
+
+ it "returns nil" do
+ expect(casted_value).to be_nil
+ end
+ end
+
+ context "when 'value' is something else" do
+ let(:value) { 123 }
+
+ it "converts it" do
+ expect(casted_value).to eq(:"123")
+ end
+ end
+ end
+end