Creating Custom Entities

You can create something other than maps or structs. To do so, you just need to tell Blacksmith how. Elixir has a JSON library called Poison. Let’s create a Forge that tells Blacksmith how to create a new JSON hash from an Elixir map, like this:

 ~~~
 defmodule JsonForge do
  use Blacksmith
 
  @new_function &Blacksmith.Config.new_json/2
 
  register :user,
  name: "John Henry",
  email: Faker.Internet.email
 end
 
 defmodule Blacksmith.Config do
  def new_json(attributes, overrides) do
  attributes
  |> Dict.merge( overrides )
  |> Poison.Encoder.encode([])
  end
 end
 ~~~

You can see a Forge with two specific enhancements. The first is the attribute variable, @new_function. Blacksmith creates maps, and that function ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.