Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/initializers/100-active-support-type-extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@

Rails.application.config.to_prepare do
ActiveModel::Type.register(:array, ActiveSupportTypeExtensions::Array)
ActiveModel::Type.register(:symbol, ActiveSupportTypeExtensions::Symbol)
end
18 changes: 18 additions & 0 deletions lib/active_support_type_extensions/symbol.rb
Original file line number Diff line number Diff line change
@@ -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
54 changes: 54 additions & 0 deletions spec/lib/active_support_type_extensions/symbol_spec.rb
Original file line number Diff line number Diff line change
@@ -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
Loading