Created
February 24, 2015 23:23
-
-
Save parroty/98a68f2e8a735434bd60 to your computer and use it in GitHub Desktop.
Macro wrapper for fetching default value of map
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 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