Skip to content

Instantly share code, notes, and snippets.

@sancero
Forked from alanpeabody/settings.ex
Last active August 29, 2015 14:19
Show Gist options
  • Save sancero/f0f722a9a07ceeee3c09 to your computer and use it in GitHub Desktop.
Save sancero/f0f722a9a07ceeee3c09 to your computer and use it in GitHub Desktop.
defmodule App.Models.Settings do
defstruct [
newsletter: false,
publish_profile: true,
email_notifications: true
]
defmodule Type do
@behaviour Ecto.Type
alias App.Models.Settings
def type, do: :json
def cast(%Settings{} = settings), do: {:ok, settings}
def cast(%{} = settings), do: {:ok, struct(Settings, settings)}
def cast(_other), do: :error
def load(value), do: Poison.decode(value, as: App.Models.Settings)
def dump(value), do: Poison.encode(value)
end
end
# and here is the jsonb version
#
defmodule App.Models.Settings do
defstruct [
newsletter: false,
publish_profile: true,
email_notifications: true
]
defmodule Type do
@behaviour Ecto.Type
alias App.Models.Settings
# ***** Change this line *****
def type, do: :jsonb
def cast(%Settings{} = settings), do: {:ok, settings}
def cast(%{} = settings), do: {:ok, struct(Settings, settings)}
def cast(_other), do: :error
def load(value), do: Poison.decode(value, as: App.Models.Settings)
# ***** Change this line *****
def dump(value), do: {:ok, value}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment