Skip to content

Instantly share code, notes, and snippets.

@skatenerd
Last active October 2, 2024 03:21
Show Gist options
  • Save skatenerd/78f838fec879e4ec1c8ac715a4815161 to your computer and use it in GitHub Desktop.
Save skatenerd/78f838fec879e4ec1c8ac715a4815161 to your computer and use it in GitHub Desktop.
Chaining `SorbetOperation::Base` operations
class BlockOperation < BaseOperation
def initialize(&blk)
@blk = blk
end
def execute
@blk.call
end
end
class BaseOperation < SorbetOperation::Base
def chain(&blk)
BlockOperation.new do
return_value = nil
my_result_object = self.perform
my_result_object.on_success do |self_result|
return_value = (yield self_result).perform
end
if return_value
return_value.unwrap!
else
raise my_result_object.unwrap_error!
end
end
end
end
class ProducesList < BaseOperation
def initialize(howmany)
@howmany = howmany
end
def execute
if @howmany == 5
raise SorbetOperation::Failure, "uh oh"
end
return ["hello"] * @howmany
end
end
class ProducesNumber < BaseOperation
def initialize(howmany)
@howmany = howmany
end
def execute
return @howmany
end
end
class Concats < BaseOperation
def initialize(items, to_add)
@items = items
@to_add = to_add
end
def execute
@items.map do |item|
item + @to_add
end
end
end
fails = ProducesNumber.new(5).chain do |n|
ProducesList.new(n).chain do |items|
Concats.new(items, n.to_s * 5)
end
end
succeeds = ProducesNumber.new(10).chain do |n|
ProducesList.new(n).chain do |items|
Concats.new(items, n.to_s * 5)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment