Runtime assertions for Ruby literal.fun
ruby
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

Results are assumed to be successful unless a failure is thrown

Updated `Literal.Result`’s block handling to assume success for returned values. Calling `success` or `failure` on the emitter throws.

This prevents you haven’t to remember to use `next` instead of `return` whern using the block.

+60 -3
+13 -3
lib/literal.rb
··· 85 85 result_type = Result::Generic.new(success_type, failure_type) 86 86 87 87 if block_given? 88 - result = yield(result_type) 89 - Literal.check(result, result_type) 90 - result 88 + caught = catch do |ball| 89 + emitter = Result::Emitter.new(type: result_type, ball:) 90 + yield(emitter) 91 + end 92 + 93 + case caught 94 + when Result::Thrown 95 + Literal.check(caught.result, result_type) 96 + caught.result 97 + else 98 + Literal.check(caught, success_type) 99 + result_type.success(caught) 100 + end 91 101 else 92 102 result_type 93 103 end
+25
lib/literal/result.rb
··· 1 1 # frozen_string_literal: true 2 2 3 3 class Literal::Result 4 + class Thrown 5 + def initialize(result) 6 + @result = result 7 + freeze 8 + end 9 + 10 + attr_reader :result 11 + end 12 + 13 + class Emitter 14 + def initialize(type:, ball:) 15 + @type = type 16 + @ball = ball 17 + freeze 18 + end 19 + 20 + def success(value) 21 + throw(@ball, Thrown.new(@type.success(value))) 22 + end 23 + 24 + def failure(error) 25 + throw(@ball, Thrown.new(@type.failure(error))) 26 + end 27 + end 28 + 4 29 class Generic 5 30 include Literal::Type 6 31
+22
test/result.test.rb
··· 11 11 assert_equal 42, result.value! 12 12 end 13 13 14 + test "result block wraps returned success values" do 15 + result = Literal::Result(Integer, Symbol) do 16 + 42 17 + end 18 + 19 + assert result.success? 20 + assert_equal 42, result.value! 21 + assert_equal Integer, result.success_type 22 + assert_equal Symbol, result.failure_type 23 + end 24 + 25 + test "result block checks returned values against success type" do 26 + error = assert_raises(Literal::TypeError) do 27 + Literal::Result(Integer, Symbol) do 28 + "42" 29 + end 30 + end 31 + 32 + assert_equal Integer, error.to_h[:expected] 33 + assert_equal "42", error.to_h[:actual] 34 + end 35 + 14 36 test "result block must return a matching result" do 15 37 assert_raises(Literal::TypeError) do 16 38 Literal::Result(Integer, Symbol) do