diff --git a/config/initializers/100-active-support-type-extensions.rb b/config/initializers/100-active-support-type-extensions.rb index 598f0df32ddc5..145d1b84094b0 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 0000000000000..2c67b3ecc04f8 --- /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 0000000000000..fba67bdd4e40e --- /dev/null +++ b/spec/lib/active_support_type_extensions/symbol_spec.rb @@ -0,0 +1,54 @@ +# 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 + # Check that the casted value equals :a_symbol + expect(casted_value).to eq(:a_symbol) + end + end + + context "when 'value' is a symbol" do + let(:value) { :a_symbol } + + it "returns it" do + # Verify that the casted value is equal to the input value + expect(casted_value).to eq(value) + end + end + + context "when 'value' is nil" do + let(:value) { nil } + + it "returns nil" do + # Assert that the casted value is equal to the nil value + expect(casted_value).to eq(value) + end + end + + context "when 'value' is blank" do + let(:value) { "" } + + it "returns nil" do + # Check that the casted value is nil + expect(casted_value).to be_nil + end + end + + context "when 'value' is something else" do + let(:value) { 123 } + + it "converts it" do + # Verify that the casted value equals the symbol :"123" + expect(casted_value).to eq(:"123") + end + end + end +end