Skip to content

Commit

Permalink
Coerce should raise if it fails
Browse files Browse the repository at this point in the history
  • Loading branch information
joeldrapper committed Dec 19, 2024
1 parent 961e8ae commit e33af9c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
10 changes: 8 additions & 2 deletions lib/literal/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,16 @@ def coerce(value)
self[value] || begin
const_get(value)
rescue NameError
nil
raise ArgumentError.new(
"Can't coerce #{value.inspect} into a #{inspect}."
)
end
else
self[value]
self[value] || raise(
ArgumentError.new(
"Can't coerce #{value.inspect} into a #{inspect}."
)
)
end
end

Expand Down
12 changes: 10 additions & 2 deletions test/enum.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,16 @@ class SymbolTypedEnum < Literal::Enum(Symbol)
assert_equal Color.coerce(:Red), Color::Red
end

test ".coerce with invalid symbol returns nil" do
assert_equal Color.coerce(:Invalid), nil
test ".coerce with invalid symbol raises an ArgumentError" do
assert_raises ArgumentError do
Color.coerce(:Invalid)
end
end

test ".coerce with invalid value raises an ArgumenError" do
assert_raises ArgumentError do
Color.coerce("invalid value")
end
end

test ".[] looks up the key by value" do
Expand Down

0 comments on commit e33af9c

Please sign in to comment.