Skip to content

Instantly share code, notes, and snippets.

@johnknott
Last active March 12, 2022 11:39
Show Gist options
  • Save johnknott/f7ccf78a0d95a2a8f7d5d17b6ee15f03 to your computer and use it in GitHub Desktop.
Save johnknott/f7ccf78a0d95a2a8f7d5d17b6ee15f03 to your computer and use it in GitHub Desktop.
VSCode snippet to help with creation of Elixir GenServers and addition of handle_call and handle_cast and related client API functions
{
"GenServer Template": {
"scope": "elixir",
"prefix": "gs",
"body": [
"defmodule ${1}.${2} do",
"\tuse GenServer",
"",
"\t# Client",
"",
"\tdef start_link(default) when is_list(default) do",
"\t\tGenServer.start_link(__MODULE__, default)",
"\tend",
"",
"\tdef push(pid, element) do",
"\t\tGenServer.cast(pid, {:push, element})",
"\tend",
"",
"\tdef pop(pid) do",
"\t\tGenServer.call(pid, :pop)",
"\tend",
"",
"\t# Server (callbacks)",
"",
"\t@impl true",
"\tdef init(stack) do",
"\t\t{:ok, stack}",
"\tend",
"",
"\t@impl true",
"\tdef handle_call(:pop, _from, [head | tail]) do",
"\t\t{:reply, head, tail}",
"\tend",
"",
"\t@impl true",
"\tdef handle_cast({:push, element}, state) do",
"\t\t{:noreply, [element | state]}",
"\tend",
"end",
"",
"# Remember to add this to your supervision tree, e.g.",
"# children = [",
"# ${1].${2}",
"# ...",
"#]",
"",
"# Supervisor.start_link(children, strategy: :one_for_all)"
],
"description": "GenServer Template"
},
"GenServer Cast": {
"prefix": "gscast",
"body": [
"def ${1:function}(${2:args}) do",
"\tGenServer.cast(__MODULE__, {:${1},{${2}}})",
"end",
"",
"@impl true",
"def handle_cast({:${1}, {${2}}}, state) do",
"\t{:noreply, state}",
"end",
"${0}"
],
"description": "GenServer cast function"
},
"GenServer Call": {
"prefix": "gscall",
"body": [
"def ${1:function}(${2:args}) do",
"\tGenServer.call(__MODULE__, {:${1},{${2}}})",
"end",
"",
"@impl true",
"def handle_call({:${1}, {${2}}}, state) do",
"\t{:reply, state}",
"end",
"${0}"
],
"description": "GenServer call function"
}
}
@johnknott
Copy link
Author

johnknott commented Mar 9, 2022

To use, add the contents of this file to a 'New snippets file' under 'File / Preferences / User Snippets' in Visual Studio code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment