Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce all keys in a struct

Tags:

struct

elixir

How could I enforce all keys in a struct without need to duplicate all the keys? To clarify, I'd like to DRY this:

defmodule Ticket do
  @enforce_keys [:origin, :destination, :price]
  defstruct [:origin, :destination, :price]
end

I can use additional variable:

defmodule Ticket do
  struct_keys = [:origin, :destination, :price]
  @enforce_keys struct_keys
  defstruct struct_keys
end

It works properly, but looks noisy. Is there any better approach?

like image 419
hedgesky Avatar asked Jan 12 '17 09:01

hedgesky


1 Answers

You can pass @enforce_keys to defstruct since @enforce_keys is just a normal module attribute:

defmodule Ticket do
  @enforce_keys [:origin, :destination, :price]
  defstruct @enforce_keys
end
iex(1)> defmodule Ticket do
...(1)>   @enforce_keys [:origin, :destination, :price]
...(1)>   defstruct @enforce_keys
...(1)> end
iex(2)> %Ticket{}
** (ArgumentError) the following keys must also be given when building struct Ticket: [:origin, :destination, :price]
    expanding struct: Ticket.__struct__/1
    iex:2: (file)
like image 146
Dogbert Avatar answered Oct 19 '22 16:10

Dogbert