StructInspect (struct_inspect v0.1.4)
View SourceProvides a mechanism to customize struct inspection by omitting fields with empty values.
By use-ing StructInspect in your struct definition, it automatically implements the
Inspect protocol for you, providing a more compact and readable representation of your
structs, especially when they contain many optional or empty fields.
Key Features
- Automatic
InspectImplementation: Simplifies the process of custom struct inspection. - Configurable Empty Values: Allows customization of what is considered an "empty" value through application configuration.
- Clean and Readable Output: Produces a cleaner inspection output by hiding noise from empty fields.
- Empty Structs: A struct is considered empty if all its fields have the default
values defined in its
defstruct. This is particularly useful for nested structs that may be initialized with default values but are not considered "empty" by default.
Examples
First, you need to define a struct and use StructInspect:
defmodule MyStruct do
@enforce_keys [:id]
defstruct [:id, :name, :age, :data]
use StructInspect
end
# Now, when you inspect instances of `MyStruct`, fields with empty values will be omitted:
%MyStruct{id: 1, name: "John", age: nil, data: %{}}
> %MyStruct{id: 1, name: "John"}You can also configure the default omitted values in your config/config.exs:
config :struct_inspect, :ommits, [:nil_value, :empty_string]
Summary
Functions
@spec __before_compile__(Macro.Env.t()) :: Macro.t()
Generates the Inspect protocol implementation for the struct.
This macro is called before the module is compiled and defines the Inspect
implementation. The implementation delegates the actual inspection logic to the
inspect/4 function.
Injects the necessary code to enable custom inspection for a struct.
This macro sets up a @before_compile hook to generate the Inspect protocol
implementation for the calling module. It also reads the default omitted values from the
application environment.
@spec inspect( map() | struct(), Inspect.Opts.t(), [atom()] | keyword() | StructInspect.Opts.t() ) :: Inspect.Algebra.t()
Filters the struct fields and builds the inspection algebra.
Parameters
data(map() | struct()) - The struct or map to be inspected.opts(Inspect.Opts.t()) - The inspection options.ommits(keyword()) - A list of atoms representing the types of empty values to omit.
Returns
Inspect.Algebra.t() - The algebra document representing the compacted struct.
@spec inspect(map(), binary(), list(), Inspect.Opts.t()) :: Inspect.Algebra.t()
Builds the inspection algebra for a map.
Parameters
map(map()) - The map to be inspected.name(binary()) - The name of the map.infos(list()) - A list of fields to be inspected.opts(Inspect.Opts.t()) - The inspection options.
Returns
Inspect.Algebra.t() - The algebra document representing the compacted map.