mbuhot

mbuhot

Validating constructor pattern?

Is there a convention/idiom for defining structs that require validation on construction?

I notice the standard library types Date and Time define a new function that returns an error tuple when the inputs are invalid:

iex> Date.new(0,0,0)
{:error, :invalid_date}

Is there any downside to declaring structs as ecto embedded_schema with a new/1 function that returns an error tuple? eg:

defmodule MyStruct do
  use Ecto.Schema
  alias Ecto.Changeset

  @primary_key false
  embedded_schema do 
    field :a, :integer
    field :b, :string
  end

  def new(attrs) do
    case cs = changeset(%MyStruct{}, attrs) do
      %{valid?: true} -> {:ok, Changeset.apply_changes(cs)}
      _ -> {:error, changeset_errors(cs)}
    end
  end

  defp changeset(data = %MyStruct{}, attrs) do
    data
    |> Changeset.cast(attrs, [:a, :b])
    |> Changset.validate_required([:a, :b])
    |> Changeset.validate_format(:b, ~r/@/)
  end

  defp changeset_errors(changeset) do
    Changeset.traverse_errors(changeset, fn {msg, opts} ->
      Enum.reduce(opts, msg, fn {key, value}, acc ->
        String.replace(acc, "%{#{key}}", to_string(value))
      end)
    end)
  end
end

Most Liked

Qqwy

Qqwy

TypeCheck Core Team

Indeed, using a new function, combined with declaring the struct’s type as @opaque (as hint that people should not construct it directly and in many cases not pattern match on it directly either) is the convention that is used for this. As for the return value in case of an error, there is no convention for this, (I have seen all of %MyStruct{} | nil, %MyStruct{} | {:error, reason} and {:ok, %MyStruct{}} | {:error, reason}; I like the third the most myself, but it depends on the situation).

As for the example with the Ecto changeset: I am not sure this is the proper way. It feels like you are partially re-inventing the logic that changesets themselves provide, but I am not immediately sure how to improve on it.

It feels more natural to me to have MyStruct.new() return a version of the struct with sensible default values (without any filled in ‘attrs’) and explicitly fill in the changeset with attrs at the place where you use it, i.e:

defmodule MyStructContext do
  def create_mystruct(attrs) do
    MyStruct.new
    |> creation_changeset(attrs)
    |> Repo.insert()
  end

  def creation_changeset(mystruct = %MyStruct, attrs) do
    mystruct
    |> MyStruct.common_changeset(attrs) # Ensures that invariants of MyStruct are never invalidated.
    |> Changeset.cast(attrs, [:someting, :only_applicable_on_creation])
    |> Changeset.validate_required([:something, :only_applicable_on_creation])
  end
end
ashneyderman

ashneyderman

I use validate_change for the embedded maps, which takes function as validator. This way you can compose validations pretty much for any imaginable structure.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement