yolo007wizard
Turn module docs and specs into a json definition?
Given the following code:
defmodule MathOps do
@moduledoc """
This module provides math operations
"""
@doc """
This function returns the sum of input
"""
@spec add(integer, integer) :: map
def add(a, b) do
%{"result" => Integer.to_string(a + b)}
end
end
I’d like to load the file and turn it into a json spec like so:
{
"module": "MathOps",
"doc": "This module provides math operations",
"defs": [
{
"name": "add",
"doc": "This function returns the sum of input",
"params": [
{"name": "a", "type": "integer", "default": null},
{"name": "b", "type": "integer", "default": null}
],
"return_type": "map"
}
]
}
Any ideas/guidance would be greatly appreciated ![]()
Marked As Solved
yolo007wizard
Geewiz I finally figured it out and as expected it was something simple. I was starting my local iex session by calling iex directly without any params.
I started iex as iex -S mix and it worked perfectly.
And now fetch_docs actually works hooray!
iex(3)> MathOps.add(1,2)
%{"result" => "3"}
iex(4)> Code.fetch_docs(MathOps)
{:docs_v1, 2, :elixir, "text/markdown",
%{"en" => "This module provides math operations\n"}, %{},
[
{{:function, :add, 2}, 6, ["add(a, b)"],
%{"en" => "This add function returns the input sum\n\n"}, %{}},
{{:function, :minus, 2}, 15, ["minus(a, b)"], :none, %{}}
]}
And for bonus points I got Exdoc working as well (which provides module specs):
config = ExDoc.Config.build("Elixir", "1", [source_beam: "beam_dir"])
docs = ExDoc.Retriever.docs_from_modules([MathOps], config)
Now I have the info I need to build the json specification ![]()
Also Liked
al2o3cr
Most of this information is also used in ExDoc templates (used to generate docs like on hexdocs.pm) so that tool’s source could be a good place to start:
yolo007wizard
Did some more reading. ExDoc is using Code.fetch_docs under the hood it seems inside defp docs_chunk. Cool I give it a try:
Code.ensure_loaded?(MathOps)
# true
Code.fetch_docs(MathOps)
# {:error, :module_not_found}
Bummer. Well after more reading I find this: Module documentation not immediatelly available after ensuring then module is compiled - #3 by josevalim. So I go down another rabbit hole trying to ensure all modules are done compiling etc get raw beam file etc and it feels overly complicated now. Hopefully someone can provide insight.
josevalim
Any module from dependencies or your lib folder will have the Docs chunk. You can try any Elixir module to get started Code.fetch_docs(String).







