9

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?

1 Answer 1

24

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)
1
  • Excellent! Thank you very much!
    – hedgesky
    Jan 12, 2017 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.