dashbitco / nimble_options

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

`:in_domain` type for option #117

Closed acalejos closed 1 year ago

acalejos commented 1 year ago

Is there any appetite for a :in_domain type to be supported directly by the library? I've been using custom type to do it but I figure that it's probably a common enough use case that others might benefit from it being in the library.

Something like:

def in_range(value, left_bracket, min, max, right_bracket) do
    in_range? =
      case {left_bracket, min, max, right_bracket} do
        {_, nil, nil, _} ->
          true

        {_, nil, max, :closed} ->
          value <= max

        {_, nil, max, :open} ->
          value < max

        {:closed, min, nil, _} ->
          value >= min

        {:open, min, nil, _} ->
          value > min

        {:closed, min, max, :closed} ->
          value >= min and value <= max

        {:open, min, max, :closed} ->
          value > min and value <= max

        {:closed, min, max, :open} ->
          value >= min and value < max

      {:open, min, max,:open} ->
                value > min and value < max
            end

          if in_range?, do: {:ok, value}, else: {:error, "Value #{value} is not in range"}
        end

EDIT: Originally I used the term range but I changed it to domain to avoid confusion w/ the keyword

josevalim commented 1 year ago

Given Elixir has the concept of range and they are always closed, my suggestion is to use our ranges, and validate on them as a struct. If you really need open/closed stuff, then I think a custom validator is indeed the way to go. :)