O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required