exconstructor v0.1.2 ExConstructor
ExConstructor is an Elixir library which makes it easier to instantiate structs from external data, such as that emitted by a JSON parser.
ExConstructor provides a define_constructor
macro which can be invoked
from a struct module. The generated constructor, called new
by default,
handles map-vs-keyword-list, string-vs-atom, and camelCase-vs-under_score
input data issues automatically, DRYing up your code and letting you
move on to the interesting parts of your program.
Installation
Add ExConstructor to your list of dependencies in
mix.exs
:def deps do [{:exconstructor, "~> 0.1.2"}] end
Ensure ExConstructor is started before your application:
def application do [applications: [:exconstructor]] end
Usage
Example:
defmodule TestStruct do
defstruct field_one: 1,
field_two: 2,
field_three: 3,
field_four: 4,
ExConstructor.define_constructor
end
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"}
Authorship and License
ExConstructor is copyright 2016 Appcues, Inc.
ExConstructor is released under the MIT License.
Summary
Macros
Defines a constructor for the struct defined in the module in which this macro was invoked. This constructor accepts a map or keyword list of keys and values. Keys may be strings or atoms, in camelCase or under_score format