jeremyjh / dialyxir

Mix tasks to simplify use of Dialyzer in Elixir projects.
Apache License 2.0
1.69k stars 141 forks source link

Q: Is it possible to access the spec in code? #411

Closed elvanja closed 4 years ago

elvanja commented 4 years ago

I need to build elastic search mappings for some structs we need to insert in ES cluster. This is something very similar to what we already define for related structs typespecs. For example, given this struct:

defmodule DemoStruct do
  @type t :: %__MODULE__{
    id: String.t(),
    status: integer(),
    descrition: String.t()
  }

  defstruct [
    :id,
    :status,
    :description
  ]
end

the resulting mapping would be:

%{
  id: %{type: "text"},
  status: %{type: "integer"},
  description: %{type: "text"}
}

So, the idea was to read the typespec for a given struct and build such a mapping from it. The motive is mostly related ti the substantial number of (nested) structs I need to define, but also because I'd like to have a consistent way of generating those vs doing it manually (which is error prone). In most cases, it would mean just traversing the spec and replacing types with appropriate ES data mapping. Hence the question, is it possible to access the spec from code? It can even be just within a mix task, since those mappings are usually created for manual execution in ES cluster. Thank you!

jeremyjh commented 4 years ago

Yes its possible, it has nothing to do with this library though its just standard Erlang. This gist looks like a good starting point: https://gist.github.com/JEG2/1685a9df2274ca5cf866122fa2dbc42d

elvanja commented 4 years ago

Excellent, thank you for the tip, looks very promising 👍

elvanja commented 4 years ago

Update: here's a related gist that works for my case https://gist.github.com/elvanja/9e63ff2306481555fd194c5631cc4f95. Do note that it is not generic enough to be applicable to all ES cases as-is, but maybe it's a good starting point.