Last active
March 5, 2022 15:13
-
-
Save tomascco/e8607692eae16ce66463d9ae4c19c4e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PicoCase | |
class Result | |
attr_reader :type, :data | |
def self.Success(**data) | |
new(:success, data) | |
end | |
def self.Failure(**data) | |
new(:failure, data) | |
end | |
def initialize(type, data) | |
@type = type | |
@data = data | |
end | |
def success? | |
type == :success | |
end | |
def failure? | |
!success? | |
end | |
def then(&block) | |
return self if failure? | |
raise LocalJumpError if block.nil? | |
block_result = ResultBlockContext.module_exec(**data, &block) | |
raise ArgumentError unless block_result.is_a?(Result) | |
block_result | |
end | |
private | |
def respond_to_missing?(name, include_private = false) | |
@data.respond_to?(name, include_private) | |
end | |
def method_missing(method, *args, &block) | |
@data.send(method, *args, &block) | |
end | |
end | |
module ResultBlockContext | |
def self.Success(**data) | |
Result.new(:success, data) | |
end | |
def self.Failure(**data) | |
Result.new(:failure, data) | |
end | |
end | |
def self.new(**data) | |
Result::Success(data) | |
end | |
end | |
pcase = PicoCase.new(number: 4) | |
puts 'no sucesso, a execução continua' | |
p pcase | |
.then { |number:| Success(number: number * 2) } | |
.then { |number:| Success(number: number + 2) } | |
puts 'na falha, a execução é cancelada' | |
p pcase | |
.then { |**| Failure() } | |
.then { |asdasdad| asdadadsa } | |
puts 'erro se o retorno não for outro Result' | |
begin | |
pcase.then { |**| 6 } | |
rescue => e | |
puts e.message | |
end | |
puts 'erro ao não usar colocar outro bloco' | |
begin | |
pcase.then | |
rescue => e | |
puts e.message | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment