Skip to content

Instantly share code, notes, and snippets.

@marcandre
Created April 17, 2023 20:23
Show Gist options
  • Save marcandre/3f66ce118551db7825914c65fb35ece4 to your computer and use it in GitHub Desktop.
Save marcandre/3f66ce118551db7825914c65fb35ece4 to your computer and use it in GitHub Desktop.
Allows calling ExVCR's `start_cassette` / `stop_cassette` from any process
defmodule Bobby.ExVcrProcess do
@moduledoc """
This GenServer allows calling `start_cassette` / `stop_cassette` from any process
# Instead of
use_cassette("x") do
do_something
end
# can be written as (each line from any process):
start_cassette("x")
do_something
stop_cassette
"""
use GenServer
use ExVCR.Mock, adapter: ExVCR.Adapter.Finch
# Callbacks
@impl true
def init(_options) do
{:ok, {nil, nil}}
end
@impl true
def handle_call(
{:start_cassette, cassette, options},
_from,
{current_recorder, _current_cassette}
) do
stop(current_recorder)
recorder = ExVCR.Mock.start_cassette(cassette, options)
{:reply, :ok, {recorder, cassette}}
end
@impl true
def handle_call(:stop_cassette, _from, {current_recorder, current_cassette}) do
stop(current_recorder)
{:reply, current_cassette, {nil, nil}}
end
defp stop(nil), do: nil
defp stop(current_recorder), do: ExVCR.Mock.stop_cassette(current_recorder)
# Public API
def start_cassette(cassette, options \\ []) do
GenServer.call(__MODULE__, {:start_cassette, cassette, options})
end
def stop_cassette do
GenServer.call(__MODULE__, :stop_cassette)
end
def start_link(options \\ []) do
GenServer.start_link(__MODULE__, options, name: __MODULE__)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment