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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With