Created
April 17, 2023 20:23
-
-
Save marcandre/3f66ce118551db7825914c65fb35ece4 to your computer and use it in GitHub Desktop.
Allows calling ExVCR's `start_cassette` / `stop_cassette` from any process
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
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