I have an Ecto schema and I am wondering about how to represent it in typespecs.
Suppose that my schema is like this:
defmodule User do
use MyApp.Model
schema "users" do
field :name, :string
field :email, :string
timestamps
end
end
Which would be the best way to refer to this struct in my specs? Currently I am doing something like:
@spec my_function(String.t) :: %User{}
But I’m thinking that I could add a @type t :: %__MODULE__{user: String.t, email: String.t} declaration to my User struct and change the specs to something like:
I believe @type t ... is the convention to define the type of module and hence should be preferred - it’s the first thing I’d try in an application. Also if you define the required keys like you showed, then you don’t have to repeat that knowledge everywhere and the source of truth lives in Schema.t
I’d say if Ecto does not already setup a typespec for your schema when it defines the struct, then I’d consider that a bug. This should happen automatically IMO.
Oh, I understand.
So, if the way to go is to manually add the typespecs to our schemas, do you think that it would be a good idea to mention it in the Ecto.Schema docs.
I think even just laying out the struct info is a good starting point. I also think that most people would implement the callback in Ecto.Type if we give good documentation on how to do it; it doesn’t sound like a very complicated task if you have a “template” to look at.
I might be wrong, but my first guess is that it would be something like quote(do: MyCustomType.t)