Programmatic access to the spec for a struct so as to generate code

I would be grateful for any suggestions on how to access the spec for a struct so that I can use that information to generate code which will make use of the field names and their types as defined in the spec.

I have looked at the modules Code and Kernel but cannot figure out how I would call to get the type’s spec in a form that I can use programmatically within my Elixir code.

I am using:

Erlang/OTP 21 [erts-10.0] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Elixir 1.6.6 (compiled with OTP 21)

All suggestions welcomed (My first post on this forum!)

When defining a struct in Elixir, you don’t have get types by default. You can get the keys however by doing something like this:

defmodule MyStruct do
  defstruct [:key_a, :key_b]
end

iex> MyStruct.__struct__() |> Map.keys()
[:__struct__, :key_a, :key_b]

To help defining structs with a type, I’ve published recently typed_struct. With this library, you can define a struct with its type and access its types through a reflexive function:

defmodule MyStruct do
  use TypedStruct

  typedstruct do
    field :key_a, String.t()
    field :key_b, integer()
  end
end

iex> MyStruct.__types__()
[
  key_a: {:|, [],
   [
     {{:., [line: 4],
       [{:__aliases__, [line: 4, counter: -576460752303422782], [:String]}, :t]},                                                
      [line: 4], []},
     nil
   ]},
  key_b: {:|, [], [{:integer, [line: 5], []}, nil]}
]

The return value of MyStruct.__types__/0 is a keyword list of keys associated to the quoted value of their type, so you can use them to define types elsewhere in your applications based on the ones from the struct.

typed_struct also defines __keys__/0 and __defaults__/0 in every struct it defines so that you can get info about the keys and their default values directly.

There is a google summer of code project to generate property based testing code based on specs. There might be something there you could look at.

Not sure where the actual code is though.

Many thanks. I will take a close look at this.

Thanks for the suggestion.