Skip to content

Commit

Permalink
Literal::Array(T) coercion (#267)
Browse files Browse the repository at this point in the history
Closes #266
  • Loading branch information
joeldrapper authored Dec 19, 2024
1 parent c35c2eb commit ae16a55
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/literal/array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ def >=(other)
def inspect
"Literal::Array(#{@type.inspect})"
end

def coerce(value)
case value
when self
value
when Array
Literal::Array.new(value, type: @type)
end
end

def to_proc
method(:coerce).to_proc
end
end

include Enumerable
Expand Down
29 changes: 29 additions & 0 deletions test/array.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,35 @@

include Literal::Types

test "coerce" do
original = ["Joel", "Stephen"]
coerced = Literal::Array(String).coerce(original)

assert_equal coerced, Literal::Array(String).new(
"Joel", "Stephen"
)
end

test "coerce with invalid values" do
original = ["Joel", "Stephen"]

assert_raises(Literal::TypeError) do
Literal::Array(Integer).coerce(original)
end
end

test "to_proc" do
mapped = [
["Joel", "Stephen"],
].map(&Literal::Array(String))

assert_equal mapped, [
Literal::Array(String).new(
"Joel", "Stephen"
),
]
end

test "===" do
assert Literal::Array(_Boolean) === Literal::Array(true).new(true)
assert Literal::Array(Object) === Literal::Array(Integer).new(1)
Expand Down

0 comments on commit ae16a55

Please sign in to comment.