diff --git a/lib/jsonapi/view.ex b/lib/jsonapi/view.ex index a21bf2bb..b2077429 100644 --- a/lib/jsonapi/view.ex +++ b/lib/jsonapi/view.ex @@ -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) @@ -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), @@ -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 @@ -161,6 +163,7 @@ defmodule JSONAPI.View do defoverridable attributes: 2, fields: 0, + hidden: 0, id: 1, meta: 2, relationships: 0, diff --git a/test/jsonapi/view_test.exs b/test/jsonapi/view_test.exs index 644a3a07..cb1ad012 100644 --- a/test/jsonapi/view_test.exs +++ b/test/jsonapi/view_test.exs @@ -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 @@ -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