You could just do something like (not perfectly efficient, but good enough
for most, and it lets the options be passed in as a list or map or any
acceptable enumeration):
```elixir
options = Map.merge(%{this_has_a_default: 42}, Enum.into(options, %{}))
options.this_is_required # Throws if use did not define
options.this_has_a_default # Uses the default value specified above if the
user did not specify it
options[:this_is_optional] # Returns null if the user did not define it
```
I have an erlang version that works on full property lists that is a lot
more efficient and can even prevent 'unknown' values from being passed in
too. I posted an Elixir'ified version of it on the forums a little bit
back.
On Friday, November 10, 2017 at 9:58:28 AM UTC-7, Christopher Keele wrote:
>
> I often want to extract a mandatory value from an options keyword list,
> and continue treating the rest as less strict configuration.
>
> This is a two-liner: mandatory = Keyword.fetch!(options, :mandatory);
> optional = Keyword.delete(options, :mandatory)
>
> I do this just often enough, I'd like to propose {mandatory, optional} =
> Keyword.pop!(options, :mandatory)
>
> - It fits in well with the current Map API
> - It's simple to implement and maintain
> - It provides an analog for the keyword variant of the (non-existent)
> positional def foo(mandatory, *optional)
>
> However it merely replaces a trivial two-liner, so this comes down to
> others in core finding the idiom common enough to merit widening the Map
> API surface area. I do, hence the proposal, but I'd love to hear
> other's experiences.
>
--
You received this message because you are subscribed to the Google Groups
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/elixir-lang-core/f386c96a-bed2-4a32-b722-74e3cb6db189%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.