Skip to content

Commit

Permalink
Fix structs support (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
fusillicode authored and aerosol committed Apr 28, 2017
1 parent f62f174 commit 5feea1d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/tabula.ex
Expand Up @@ -47,6 +47,7 @@ defmodule Tabula do
end

defprotocol Row do
@fallback_to_any true
def get(row, col, default \\ nil)
def keys(row)
end
Expand All @@ -61,6 +62,11 @@ defmodule Tabula do
def keys(row), do: row |> Keyword.keys
end

defimpl Row, for: Any do
def get(%{__struct__: _} = row, col, default \\ nil), do: row |> Map.get(col, default)
def keys(row), do: row |> Map.from_struct |> Map.keys
end

def print_table(rows, opts \\ []) do
render_table(rows, opts)
|> IO.puts
Expand Down
24 changes: 24 additions & 0 deletions test/tabula_test.exs
Expand Up @@ -160,4 +160,28 @@ defmodule TabulaTest do
"""
assert table == expect
end

test "Prints the expected results for collections of Structs" do
rows = [%Point{x: 0, y: 0}, %Point{x: 1, y: 0}]
table = Tabula.render_table(rows)

expect = """
:x | :y
---+---
0 | 0
1 | 0
"""
assert table == expect
end

test "Tabula.Row.get" do
assert Tabula.Row.get(%{x: 0, y: 0}, :x) == 0
assert Tabula.Row.get([x: 0, y: 0], :x) == 0
end

test "Tabula.Row.keys" do
assert Tabula.Row.keys([x: 0, y: 0]) == ~w(x y)a
assert Tabula.Row.keys(%{x: 0, y: 0}) == ~w(x y)a
assert Tabula.Row.keys(%Point{x: 0, y: 0}) == ~w(x y)a
end
end

0 comments on commit 5feea1d

Please sign in to comment.