From 0eff2f77d0ae3dfb9def11a696afd338df993a54 Mon Sep 17 00:00:00 2001 From: Max VelDink Date: Tue, 9 Jul 2024 13:20:18 -0400 Subject: [PATCH] feat: Add clearer message for CoercionNotSupportedError (#113) --- lib/typed/coercion.rb | 6 +++--- lib/typed/coercion/coercion_not_supported_error.rb | 9 ++++++++- .../coercion/coercion_not_supported_error_test.rb | 11 +++++++++++ test/typed/coercion_test.rb | 2 +- 4 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 test/typed/coercion/coercion_not_supported_error_test.rb diff --git a/lib/typed/coercion.rb b/lib/typed/coercion.rb index b87be3f..18b37bd 100644 --- a/lib/typed/coercion.rb +++ b/lib/typed/coercion.rb @@ -11,11 +11,11 @@ def self.register_coercer(coercer) sig { type_parameters(:U).params(type: T::Types::Base, value: Value).returns(Result[Value, CoercionError]) } def self.coerce(type:, value:) - coercer = CoercerRegistry.instance.select_coercer_by(type: type) + coercer = CoercerRegistry.instance.select_coercer_by(type:) - return Failure.new(CoercionNotSupportedError.new) unless coercer + return Failure.new(CoercionNotSupportedError.new(type:)) unless coercer - coercer.new.coerce(type: type, value: value) + coercer.new.coerce(type:, value:) end end end diff --git a/lib/typed/coercion/coercion_not_supported_error.rb b/lib/typed/coercion/coercion_not_supported_error.rb index 4727e67..94d5e90 100644 --- a/lib/typed/coercion/coercion_not_supported_error.rb +++ b/lib/typed/coercion/coercion_not_supported_error.rb @@ -2,6 +2,13 @@ module Typed module Coercion - class CoercionNotSupportedError < CoercionError; end + class CoercionNotSupportedError < CoercionError + extend T::Sig + + sig { params(type: T::Types::Base).void } + def initialize(type:) + super("Coercer not found for type #{type}.") + end + end end end diff --git a/test/typed/coercion/coercion_not_supported_error_test.rb b/test/typed/coercion/coercion_not_supported_error_test.rb new file mode 100644 index 0000000..2a72b38 --- /dev/null +++ b/test/typed/coercion/coercion_not_supported_error_test.rb @@ -0,0 +1,11 @@ +# typed: true + +require "test_helper" + +class CoercionNotSupportedErrorTest < Minitest::Test + def test_formats_message + error = Typed::Coercion::CoercionNotSupportedError.new(type: T::Utils.coerce(RubyRank)) + + assert_equal("Coercer not found for type RubyRank.", error.message) + end +end diff --git a/test/typed/coercion_test.rb b/test/typed/coercion_test.rb index ee2db17..2f79bad 100644 --- a/test/typed/coercion_test.rb +++ b/test/typed/coercion_test.rb @@ -24,6 +24,6 @@ def test_when_coercer_isnt_matched_coerce_returns_failure result = Typed::Coercion.coerce(type: T::Utils.coerce(BigDecimal), value: "testing") assert_failure(result) - assert_error(Typed::Coercion::CoercionNotSupportedError.new, result) + assert_error(Typed::Coercion::CoercionNotSupportedError.new(type: T::Utils.coerce(BigDecimal)), result) end end