Skip to content

Commit

Permalink
Add hidden/0 to view (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
doomspork authored and Jason S committed Jul 12, 2017
1 parent 1bbe4de commit 3c73e87
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
9 changes: 6 additions & 3 deletions lib/jsonapi/view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,7 @@ defmodule JSONAPI.View do

#TODO Figure out the nesting of fields
def attributes(data, conn) do
underscore_to_dash = Application.get_env(:jsonapi, :underscore_to_dash, false)

data = Map.take(data, fields())
data = visible_fields(data)

if underscore?() do
underscore(data)
Expand All @@ -99,6 +97,8 @@ defmodule JSONAPI.View do

def fields, do: raise "Need to implement fields/0"

def hidden, do: []

def show(model, conn, _params),
do: serialize(__MODULE__, model, conn)
def index(models, conn, _params),
Expand Down Expand Up @@ -140,6 +140,8 @@ defmodule JSONAPI.View do
do: index(data, conn, params)
end

defp visible_fields(data), do: Map.take(data, fields() -- hidden())

defp underscore?, do: Application.get_env(:jsonapi, :underscore_to_dash, false)

defp underscore(data) do
Expand All @@ -161,6 +163,7 @@ defmodule JSONAPI.View do

defoverridable attributes: 2,
fields: 0,
hidden: 0,
id: 1,
meta: 2,
relationships: 0,
Expand Down
12 changes: 11 additions & 1 deletion test/jsonapi/view_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ defmodule JSONAPI.ViewTest do
namespace: "/api"

def fields do
[:age, :first_name, :last_name]
[:age, :first_name, :last_name, :password]
end

def hidden do
[:password]
end
end

Expand Down Expand Up @@ -64,9 +68,15 @@ defmodule JSONAPI.ViewTest do
refute {:render, 2} in PostView.__info__(:functions)
end

test "attributes/2 does not display hidden fields" do
expected_map = %{age: 100, first_name: "Jason", last_name: "S"}
assert expected_map == UserView.attributes(%{age: 100, first_name: "Jason", last_name: "S", password: "securepw"}, nil)
end

test "attributes/2 with `:underscore_to_dash` option" do
Application.put_env(:jsonapi, :underscore_to_dash, true)
expected_map = %{age: 100, "first-name": "Jason", "last-name": "S"}
assert expected_map == UserView.attributes(%{age: 100, first_name: "Jason", last_name: "S"}, nil)
Application.put_env(:jsonapi, :underscore_to_dash, false)
end
end

0 comments on commit 3c73e87

Please sign in to comment.