Last active
August 29, 2015 14:04
-
-
Save khia/1106f6bed847cee96340 to your computer and use it in GitHub Desktop.
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 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