Skip to content

Instantly share code, notes, and snippets.

@krzykamil
Created October 25, 2023 09:18
Show Gist options
  • Save krzykamil/b53f66443217b6b5b92ab6085b853908 to your computer and use it in GitHub Desktop.
Save krzykamil/b53f66443217b6b5b92ab6085b853908 to your computer and use it in GitHub Desktop.
Interrupt - dry-effects error flow
# frozen_string_literal: true
require 'dry/effects'
class LoginManager
include Dry::Effects::Handler.Interrupt(:invalid_credentials, as: :catch_invalid_credentials)
def call
error, message = catch_invalid_credentials do
yield
end
error ? :error : message
end
end
class Authenticate
include Dry::Effects.Interrupt(:invalid_credentials)
def call(email, password)
(email == 'ksysio@mail.com' && password == 'secure') ? "Logged in, welcome!" : invalid_credentials
end
end
run = LoginManager.new
auth = Authenticate.new
# Mocks up a situation, where inside an app, we want to log the user in
app = -> email, pass do
run.() do
auth.(email, pass)
end
end
puts app.('ksysio@mail.com', 'secure')
puts app.('sarin@to.boss', 'secure')
# frozen_string_literal: true
require 'dry/effects'
class TemperatureSensor
include Dry::Effects.Interrupt(:location_error)
def read_temperature(location)
if location == 'Warszawa'
25.0
elsif location == 'Białystok'
10.0
else
location_error "Invalid location, but the closest location we know of, has temperature: 666.69"
end
end
end
class WeatherReporter
include Dry::Effects::Handler.Interrupt(:location_error, as: :catch_location_error)
def report_weather(location)
_, result = catch_location_error do
"Temperature at #{location} is: #{yield}"
end
result
end
end
report_system = WeatherReporter.new
temperature_monitoring_system = TemperatureSensor.new
puts report_system.report_weather("Białystok") { temperature_monitoring_system.read_temperature("Białystok") }
puts report_system.report_weather("Warszawa") { temperature_monitoring_system.read_temperature("Warszawa") }
puts report_system.report_weather("hell") { temperature_monitoring_system.read_temperature("hell") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment