dry-rb / dry-effects

Algebraic effects in Ruby
https://dry-rb.org/gems/dry-effects/
MIT License
112 stars 20 forks source link

Interrupt example from documentation not working #67

Closed citizen428 closed 4 years ago

citizen428 commented 4 years ago

Describe the bug

Executing the code from the Basic Usage of the Interrupt guide does not yield the expected result.

To Reproduce

Execute the code from the example:

require 'dry/effects'

class RunDivision
  include Dry::Effects::Handler.Interrupt(:division_by_zero, as: :catch_zero_division)

  def call
    success, answer = catch_zero_division do
      yield
    end

    if success
      answer
    else
      :error
    end
  end
end

class Divide
  include Dry::Effects.Interrupt(:division_by_zero)

  def call(dividend, divisor)
    if divisor.zero?
      division_by_zero
    else
      dividend / divisor
    end
  end
end

run = RunDivision.new
divide = Divide.new

app = -> a, b { run.() { divide.(a, b) } }

Expected behavior

Expected:

app.(10, 2) # => 5
app.(1, 0) # => :error

Got:

app.(10, 2) # => :error
app.(1, 0) # => nil

Your environment

I'd look into it myself, but won't have time today.

citizen428 commented 4 years ago

It seems like the first value in the return "tuple" is actually switched. If we treat the first return value as error instead of success everything works as expected:

require 'dry/effects'

class RunDivision
  include Dry::Effects::Handler.Interrupt(:division_by_zero, as: :catch_zero_division)

  def call
    error, answer = catch_zero_division do
      yield
    end

    if error
      :error
    else
      answer
    end
  end
end

class Divide
  include Dry::Effects.Interrupt(:division_by_zero)

  def call(dividend, divisor)
    if divisor.zero?
      division_by_zero
    else
      dividend / divisor
    end
  end
end

run = RunDivision.new
divide = Divide.new

app = -> a, b { run.() { divide.(a, b) } }

run = RunDivision.new
divide = Divide.new

app = -> a, b { run.() { divide.(a, b) } }
app.(10, 2) # => 5
app.(10, 2) # => :error
flash-gordon commented 4 years ago

Thanks!