Using `Ash.Type.String` like `Ash.Type.Enum`

What I'm imagining: lib/bookstore/types/isbn.ex:
defmodule Bookstore.Type.ISBN do
use Ash.String, match: ~r/((978[\--– ])?[0-9][0-9\--– ]{10}[\--– ][0-9xX])|((978)?[0-9]{9}[0-9Xx])/
end
defmodule Bookstore.Type.ISBN do
use Ash.String, match: ~r/((978[\--– ])?[0-9][0-9\--– ]{10}[\--– ][0-9xX])|((978)?[0-9]{9}[0-9Xx])/
end
lib/bookstore/resources/book.ex:
defmodule Bookstore.Book do
alias Bookstore.Type
attributes do
attribute :isbn, ISBN
end
end
defmodule Bookstore.Book do
alias Bookstore.Type
attributes do
attribute :isbn, ISBN
end
end
Seems like it would be good to be able to reuse and narrow many of the core types this way. Thoughts?
6 Replies
ZachDaniel
ZachDaniel3y ago
I think that makes sense, but also keep in mind you can effectively do that with a custom type currently.
defmodule Bookstore.Type.ISBN do
use Ash.Type

def cast_input(value, constraints) do
case Ash.Type.String.cast_input(value, constraints) do
{:ok, type} ->
if String.match?(string, ~r//) do
else
end
end
end

...
end
defmodule Bookstore.Type.ISBN do
use Ash.Type

def cast_input(value, constraints) do
case Ash.Type.String.cast_input(value, constraints) do
{:ok, type} ->
if String.match?(string, ~r//) do
else
end
end
end

...
end
However, I see the value for what you're getting at up there. What I'd actually like to see is the ability to create a generic NewType (this is the term in most type systems). The NewType would simply package up some constraints on another type
defmodule Bookstore.Type.ISBN do
use Ash.Type, type_of: :string, constraints: [match: ~r//]
end
defmodule Bookstore.Type.ISBN do
use Ash.Type, type_of: :string, constraints: [match: ~r//]
end
Actually I really want that to exist, because that will help with many types. For example:
defmodule MyApp.Types.PositiveInteger do
use Ash.Type, type_of: :integer, constraints: [min: 1]
end
defmodule MyApp.Types.PositiveInteger do
use Ash.Type, type_of: :integer, constraints: [min: 1]
end
\ ឵឵឵
\ ឵឵឵OP3y ago
That's right along my line of thought. This stuff can be accomplished using Ash.Type, but it would be great to have a more concise way to express a large portion of common cases.
ZachDaniel
ZachDaniel3y ago
Honestly, its an easy change to make so I'm going to have a go at it 😄
\ ឵឵឵
\ ឵឵឵OP3y ago
Awesome!
ZachDaniel
ZachDaniel3y ago
This has been released as Ash.Type.NewType
\ ឵឵឵
\ ឵឵឵OP3y ago
Great! Using it right now. It's a pleasure to work with a project that has responsive maintainers 👍

Did you find this page helpful?