Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added encoding function for tuple datatype #211

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions lib/poison/encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,47 @@ defprotocol Poison.Encoder do
def encode(value, options)
end

defimpl Poison.Encoder, for: Tuple do
alias Poison.{Encoder, Pretty}

use Poison.{Encode, Pretty}

@compile :inline
@compile :inline_list_funcs

def encode({}, _options), do: "{}"

def encode(tuple, options) do
tuple_to_list = Tuple.to_list(tuple)
encode(tuple_to_list, pretty(options), options)
end

@spec encode(list, boolean, any) :: [...]
def encode(tuple_to_list, false, options) do
[?{, tl(:lists.foldr(&[?,, Encoder.encode(&1, options) | &2], [], tuple_to_list)), ?}]
end

def encode(tuple_to_list, true, options) do
indent = indent(options)
offset = offset(options) + indent
options = offset(options, offset)

[
"{\n",
tl(
:lists.foldr(
&[",\n", spaces(offset), Encoder.encode(&1, options) | &2],
[],
tuple_to_list
)
),
?\n,
spaces(offset - indent),
?}
]
end
end

defimpl Poison.Encoder, for: Atom do
def encode(nil, _options), do: "null"
def encode(true, _options), do: "true"
Expand Down
6 changes: 6 additions & 0 deletions test/poison/encoder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ defmodule Poison.EncoderTest do
end
end

property "Tuple" do
check all(value <- json_list(min_length: 1)) do
assert String.match?(to_json({value}), ~r/^\{.*\}$/)
end
end

test "Map" do
assert to_json(%{}) == "{}"
assert to_json(%{"foo" => "bar"}) == ~s({"foo":"bar"})
Expand Down