ExConstructor is an Elixir library designed to simplify instantiating structs from external data sources (like JSON parsers). By adding use ExConstructor to a module, you inject a constructor function (defaulting to new/1) that automatically resolves common data format mismatches, including:
- Map vs. Keyword List: Handles both input types.
- String vs. Atom Keys: Automatically converts string keys to atoms.
- camelCase vs. under_score: Normalizes camelCase keys to match the struct's under_scored field names.
This allows you to pass messy external maps directly into your struct constructor.
defmodule TestStruct do
use ExConstructor
defstruct field_one: nil,
field_two: nil,
field_three: nil,
field_four: nil
end
# The constructor handles mixed key types and casing automatically
TestStruct.new(%{"field_one" => "a", "fieldTwo" => "b", :field_three => "c", :FieldFour => "d"})
# => %TestStruct{field_one: "a", field_two: "b", field_three: "c", field_four: "d"}