Skip to content

Instantly share code, notes, and snippets.

@parroty
Created February 24, 2015 23:23
Show Gist options
  • Save parroty/98a68f2e8a735434bd60 to your computer and use it in GitHub Desktop.
Save parroty/98a68f2e8a735434bd60 to your computer and use it in GitHub Desktop.
Macro wrapper for fetching default value of map
defmodule Fetcher do
def db_value_for(key) do
IO.puts "processing..."
"db value for #{key}"
end
defmacro get(map, key, default \\ nil) do
quote do
case Map.get(unquote(map), unquote(key)) do
nil -> unquote(default)
value -> value
end
end
end
def run do
map = %{x: 1}
IO.puts get(map, :x, db_value_for(:x))
IO.puts get(map, :z, db_value_for(:z))
end
end
Fetcher.run()
# iex(2)> Fetcher.run()
# 1
# processing...
# db value for z
# :ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment