exconstructor v0.1.0 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-dict, 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

  1. Add ExConstructor to your list of dependencies in mix.exs:

    def deps do
      [{:exconstructor, "~> 0.1.0"}]
    end
  2. Ensure ExConstructor is started before your application:

    def application do
      [applications: [:exconstructor]]
    end

Usage

Example:

iex(1)> defmodule TestStruct do
...(1)>   import ExConstructor
...(1)>   defstruct field_one: 1,
...(1)>             field_two: 2,
...(1)>             field_three: 3,
...(1)>             field_four: 4,
...(1)>             field_five: 5
...(1)>   define_constructor
...(1)> end
iex(2)> 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", field_five: 5}

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 dict of keys and values. Keys may be strings or atoms, in camelCase or under_score format

Macros

define_constructor(function_name \\ :new)

Defines a constructor for the struct defined in the module in which this macro was invoked. This constructor accepts a map or dict of keys and values. Keys may be strings or atoms, in camelCase or under_score format.