Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
defmodule Instrument do
@zero :decimal_conv.number("0")
@struct symbol: nil, name: "", value: @zero
defstruct @struct
@keys Enum.sort(@struct |> Map.keys |> List.delete(:__struct__))
for k <- @keys do
def __atomize__({unquote(Atom.to_string(k)), v}, acc) do
Dict.put(acc, unquote(k), v)
end
def __atomize__({unquote(k), v}, acc) do
Dict.put(acc, unquote(k), v)
end
end
def __atomize__(_, acc), do: acc
def new(kv) do
kv = Enum.reduce(kv, %{}, &__atomize__/2)
kv = Dict.update(kv, :value, @zero,
fn(v) -> :decimal_conv.number(v) end)
struct(__MODULE__, kv)
end
def value(record, amount) do
%{record | value: :decimal_conv.number(amount)}
end
def struct?(%{__struct__: struct} = map, struct) do
map = Map.delete(map, :__struct__) # To prevent protocol dispatch
atomized_map = Enum.reduce(map, %{}, &__atomize__/2)
Enum.sort(Map.keys(atomized_map)) == @keys
end
def struct?(_, _), do: false
def struct?(map), do: is_struct(map, __MODULE__)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.