Skip to content

Instantly share code, notes, and snippets.

@creadone
Created February 22, 2021 18:37
Show Gist options
  • Save creadone/2a1080eef16c2a1835d009a8723066c1 to your computer and use it in GitHub Desktop.
Save creadone/2a1080eef16c2a1835d009a8723066c1 to your computer and use it in GitHub Desktop.
Helper to wrap external API requests
class Cocoon(T)
def initialize(
@result = Channel(T | Exception).new,
@output = Channel(T | Exception).new
)
end
def wrap(&block : -> T) forall T
spawn(name: "executor") do
@result.send block.call
rescue e
@result.send e
end
Fiber.yield
spawn(name: "receiver") do
select
when data = @result.receive
@output.send data
end
end
@output
end
end
# -----
cocoon = Cocoon(HTTP::Client::Response).new
result = cocoon.wrap do
HTTP::Client.get "localhost:9292"
end
result.receive
#=> <HTTP::Client::Response...>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment