Skip to content

Instantly share code, notes, and snippets.

@ninjapanzer
Created March 23, 2023 06:11
Show Gist options
  • Save ninjapanzer/818757b6faf2850f9951974d80163cf4 to your computer and use it in GitHub Desktop.
Save ninjapanzer/818757b6faf2850f9951974d80163cf4 to your computer and use it in GitHub Desktop.
Sorbet Generics
module MyModule
class HandlerInterface
extend T::Helpers
extend T::Sig
abstract!
sig { abstract.params(input: T::Struct).returns(T::Struct) }
def success_handler(input); end
end
end
class CustomHandler < MyModule::HandlerInterface
def success_handler(input)
# Perform the successful operation
response_data = do_something_with_input(input.data)
# Return a CustomReturnType object with the response data
CustomReturnType.new(result: response_data)
end
end
module MyModule
class Action
extend T::Sig
sig do
params(
handler: HandlerInterface,
request: Request,
error_handler: T.nilable(T.proc.params(error: StandardError).returns(T::Struct)),
config: T.nilable(Config)
).void
end
def initialize(handler, request, error_handler = nil, config = nil)
@handler = T.let(handler, HandlerInterface)
@error_handler = T.let(error_handler, T.nilable(T.proc.params(error: StandardError).returns(T::Struct)))
@request = T.let(request, Request)
@config = T.let(config || Config.global, Config)
end
sig { params(input: T::Struct).returns(T::Struct) }
def submit(input)
@request.klass = @handler.class
@request.input = input
begin
@config.middleware.invoke(@request) do
@handler.success_handler(input)
end
rescue StandardError => e
@error_handler ? @error_handler.call(e) : ErrorResult.new(error: e)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment