Skip to content

Commit

Permalink
Allow map options in validate/2 when schema is a list
Browse files Browse the repository at this point in the history
It works when the schema is a NimbleOptions struct because of the function match, but not when it's just a list
  • Loading branch information
cheerfulstoic committed Aug 1, 2024
1 parent 19a9edd commit df1b34e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/nimble_options.ex
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ defmodule NimbleOptions do
validate_options_with_schema(options, schema)
end

def validate(options, schema) when is_list(options) and is_list(schema) do
def validate(options, schema) when (is_list(options) or is_map(options)) and is_list(schema) do
validate(options, new!(schema))
end

Expand Down
26 changes: 26 additions & 0 deletions test/nimble_options_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1735,6 +1735,32 @@ defmodule NimbleOptionsTest do
end
end

# No other test is passing in `opts` as a map, so these are just some white box tests for sanity checking
describe "can use a map for validate/2" do
schema = []
opts = %{}
assert NimbleOptions.validate(opts, schema) == {:ok, %{}}

schema = [
name: [type: :string, required: true],
context: [type: :atom, required: false]
]

opts = %{}

assert NimbleOptions.validate(opts, schema) ==
{:error,
%ValidationError{
key: :name,
value: nil,
keys_path: [],
message: "required :name option not found, received options: []"
}}

opts = %{name: "primary 1"}
assert NimbleOptions.validate(opts, schema) == {:ok, %{name: "primary 1"}}
end

describe "validate!/2 (raising version)" do
test "returns the direct options if the options are valid" do
schema = [name: [], context: []]
Expand Down

0 comments on commit df1b34e

Please sign in to comment.