Skip to content

Instantly share code, notes, and snippets.

@voughtdq
Created June 19, 2022 19:52
Show Gist options
  • Save voughtdq/a4930fd9c8ce10f2899a3476e94aba1a to your computer and use it in GitHub Desktop.
Save voughtdq/a4930fd9c8ce10f2899a3476e94aba1a to your computer and use it in GitHub Desktop.
An atom type implementation for Ecto that allows trusted fields to be unconditionally casted to atoms and loaded into atoms.
defmodule Ecto.Atom do
# MIT License
#
# Copyright (c) 2017 Matthieu Pinte
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
@moduledoc """
An atom type implementation for Ecto that allows trusted field to be
unconditionally converted to atoms.
## Usage
defmodule FooBar do
use Ecto.Schema
schema "foo_bars" do
field :baz, Ecto.Atom, trusted: true # will use String.to_atom/1
field :buzz, Ecto.Atom # same as trusted: false,
# will use String.to_existing_atom/1
end
end
"""
use Ecto.ParameterizedType
@impl true
def type(_params), do: :string
@impl true
def init(opts) do
trusted = Keyword.get(opts, :trusted, false)
%{trusted: trusted}
end
@impl true
def cast(value, _params) when is_atom(value), do: {:ok, value}
def cast(value, %{trusted: true}), do: {:ok, String.to_atom(value)}
def cast(value, %{trusted: false}), do: {:ok, String.to_existing_atom(value)}
def cast(_value, _params), do: :error
@impl true
def load(nil, _loader, _params), do: {:ok, nil}
def load(value, _loader, %{trusted: true}), do: {:ok, String.to_atom(value)}
def load(value, _loader, %{trusted: false}), do: {:ok, String.to_existing_atom(value)}
@impl true
def dump(value, _dumper, _params) when is_atom(value), do: {:ok, Atom.to_string(value)}
def dump(_value, _dumper, _params), do: :error
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment