dashbitco / nimble_options

A tiny library for validating and documenting high-level options. 💽
Apache License 2.0
507 stars 38 forks source link

Validate certain params and allow to have extra ones #136

Closed rockneurotiko closed 2 months ago

rockneurotiko commented 2 months ago

We are doing a internally wrapper of a library (Req), where we'll require certain params to be passed but others will be just the same as Req, we wanted to use NimbleOptions to validate the required params but allow any other param, and I don't know if it's not possible, it's a bug, or I don't know how to build the schema for this behaviour.

Here is a simple example of what we wanted:

schema = [name: [type: :atom, required: true], *: [type: :any]]
opts = [name: :some_name, other_value: 2]
NimbleOptions.validate(opts, schema)

With this schema it doesn't validate the :name option at all, I guess *: has priority:

iex(11)> NimbleOptions.validate([], schema)
{:ok, []}
iex(12)> NimbleOptions.validate([name: "a"], schema)
{:ok, [name: "a"]}
wojtekmach commented 2 months ago

I'm -1 on allowing arbitrary option names.

I think you can do the following today:

{known_options, other_options} = Keyword.split(options, [:a, :b])
NimbleOptions.validate(known_options, schema)

Btw, in Req you can grab the options Req knows of: Req.new().registered_options and you can assign an any type to them. It's not documented at the moment but I'd be happy to add a public API: Req.Request.registered_option_names(req)`, a PR would be appreciated.

I'm going to close this but happy to continue the conversation.