Skip to content

Commit

Permalink
Merge pull request #13 from jfacorro/jfacorro.12.encode_impl_for_any
Browse files Browse the repository at this point in the history
[Closes #12] Encode protocol implementation for Any, but actually only for s…
  • Loading branch information
jfacorro committed Jun 10, 2015
2 parents e9cce1e + d5bd79f commit 5cdce8b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/ex_edn/encode.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ alias ExEdn.UUID
alias ExEdn.Tag

defprotocol ExEdn.Encode do
@fallback_to_any true
def encode(value)
end

Expand Down Expand Up @@ -101,3 +102,12 @@ defimpl Encode, for: Timex.DateTime do
Encode.encode(Tag.new("inst", value))
end
end

defimpl Encode, for: Any do
def encode(struct) when is_map(struct) do
Encode.encode(Map.from_struct(struct))
end
def encode(_) do
raise Protocol.UndefinedError
end
end
6 changes: 6 additions & 0 deletions test/ex_edn_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ defmodule ExEdnTest do
assert encode!(some_tag) == "#custom/tag :joni"
end

test "Encode Fallback to Any" do
node = %ExEdn.Parser.Node{}
map = Map.from_struct(node)
assert encode!(node) == encode!(map)
end

test "Encode Unknown Type" do
e = %Protocol.UndefinedError{}
assert encode(self) == {:error, e.__struct__}
Expand Down

0 comments on commit 5cdce8b

Please sign in to comment.