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

Add a way to customize which json library to use #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 7 additions & 4 deletions lib/trunk/state.ex
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ defmodule Trunk.State do
filename
end

defp(save_as(state, :json, opts), do: state |> save_as(:map, opts) |> json_parser().encode!())
defp(save_as(state, :json, opts), do: state |> save_as(:map, opts) |> json_library().encode!())

defp save_as(%{filename: filename, assigns: assigns, versions: versions}, :map, opts) do
assigns_to_save = Keyword.get(opts, :assigns, :all)
Expand Down Expand Up @@ -230,7 +230,7 @@ defmodule Trunk.State do
def restore(file_info, opts \\ [])

def restore(<<"{", _rest::binary>> = json, opts) do
{:ok, map} = json_parser().decode(json)
{:ok, map} = json_library().decode(json)

map
|> keys_to_atom
Expand Down Expand Up @@ -271,16 +271,19 @@ defmodule Trunk.State do

defp keys_to_atom(arg), do: arg

defp json_parser do
defp json_library do
cond do
Application.get_env(:trunk, :json_library) ->
Application.get_env(:trunk, :json_library)

Code.ensure_loaded?(Jason) ->
Jason

Code.ensure_loaded?(Poison) ->
Poison

raise RuntimeError,
"You must have a JSON parser loaded (Jason and Poison are supported)"
"You must have a JSON library loaded (Jason and Poison are supported or specify your own with `config :trunk, json_library: Jason`)"
end
end
end