Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add built-in number type #41

Merged
merged 2 commits into from
Jan 30, 2024
Merged

Add built-in number type #41

merged 2 commits into from
Jan 30, 2024

Conversation

solnic
Copy link
Owner

@solnic solnic commented Jan 26, 2024

This adds a built-in Number type, which is just a union([:integer, :float]) under the hood:

defmodule ProductContract do
  use Drops.Contract

  schema do
    %{
      required(:name) => string(:filled?),
      required(:price) => number()
    }
  end
end

ProductContract.conform(%{name: "Book", price: 31.2})
# {:ok, %{name: "Book", price: 31.2}}

ProductContract.conform(%{name: "Book", price: 31})
# {:ok, %{name: "Book", price: 31}}

{:error, errors} = ProductContract.conform(%{name: "Book", price: []})
Enum.map(errors, &to_string/1)
# ["price must be a number"]

This type required making use of type opts, which now can be declared as an @opts module attribute in your custom types. The Number type is defined as:

defmodule Drops.Types.Number do
  use(Drops.Type, union([:integer, :float]))

  @opts name: :number
end

The :name option is then used to return a simple error message instead of the default union error like foo must be an integer or foo must be a float.

Using opts will be leveraged more by other future features.

refs #33

@solnic solnic marked this pull request as ready for review January 30, 2024 07:31
@solnic solnic merged commit 3be9fd7 into main Jan 30, 2024
9 checks passed
@solnic solnic deleted the number-type branch January 30, 2024 07:31
@solnic solnic mentioned this pull request Jan 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

1 participant