A TypedStruct plugin allows you to extend the typedstruct block by injecting custom logic, helpers, or metadata for the struct and its fields. To create a plugin, define a module that uses TypedStruct.Plugin.
There are three primary lifecycle callbacks you can implement:
init(opts): Injects code at the point where plugin/2 is called inside the typedstruct block. This is useful for importing custom macros or setting up module-level state (like module attributes) that the plugin will use during the definition process.field(name, type, opts, env): Injects code for every field defined via the field/3 macro. The opts argument contains a concatenation of the options passed directly to the field macro and any options provided during the plugin's init phase. The env argument provides the macro environment at the time of definition.after_definition(opts): Injects code after the entire struct and its type have been defined. This is ideal for cleanup tasks, such as deleting temporary module attributes used during the build process.
Using TypedStruct.Plugin provides default implementations for these callbacks, so you only need to implement the ones you require.
defmodule MyCustomPlugin do
use TypedStruct.Plugin
@impl true
defmacro init(opts) do
quote do
# Code to inject when 'plugin MyCustomPlugin' is called
end
end
@impl true
def field(name, type, opts, env) do
quote do
# Code to inject for each field
end
end
@impl true
def after_definition(opts) do
quote do
# Code to inject after the struct is defined
end
end
end