Maru.Entity (maru_entity v0.2.4) View Source

Defining Entities

Basic Exposure

expose :id

expose with Map.get(instance, :id)

%{id: 1} => %{id: 1}

Exposing with a Presenter

expose field with another entity and another key:

expose :response, source: :reply, using: Reply.Entity

%{reply: reply} => %{response: Reply.Entity.serializer(reply)}

expose list-type field with another entity:

expose :replies, using: List[Reply.Entity]

%{replies: [reply1, reply2]} => %{replies: [Reply.Entity.serializer(reply1), Reply.Entity.serializer(reply2)]}

Conditional Exposure

Use :if or :unless to expose fields conditionally.

expose :username, if: fn(user, _options) -> user[:public?] end

%{username: "user1", public?: true} => %{username: "user1"}

%{username: "user1", public?: false} => %{}

Custom Present Function

expose :username, [], fn user, _options ->
  "#{user[:first_name]} #{user[:last_name]}"
end

%{first_name: "X", last_name: "Y"} => %{username: "X Y"}

Link to this section Summary

Functions

Generate default runtime struct.

Expose a field or a set of fields with Map.get.

Depends on the second parameter is a function or list

Expose a field or a set of fields with custom function and options.

Extend another entity.

Link to this section Types

Specs

group() :: [atom()]

Specs

instance() :: map()

Specs

object() :: map()

Specs

one_or_many() :: :one | :many

Specs

options() :: map()

Link to this section Functions

Link to this function

default_runtime(atom, group)

View Source

Specs

default_runtime(atom(), group()) :: Macro.t()

Generate default runtime struct.

Link to this macro

expose(attr_or_attrs)

View Source (macro)

Expose a field or a set of fields with Map.get.

Link to this macro

expose(group, options)

View Source (macro)

Depends on the second parameter is a function or list:

  1. Expose a field or a set of fields with Map.get and options.
  2. Expose a field or a set of fields with custom function without options.
Link to this macro

expose(attr_or_attrs, options, do_func)

View Source (macro)

Expose a field or a set of fields with custom function and options.

Link to this macro

extend(module, options \\ [])

View Source (macro)

Extend another entity.

Example:

defmodule UserData do
  use Maru.Entity
  expose :name
  expose :address do
    expose :address1
    expose :address2
    expose :address_state
    expose :address_city
  end
  expose :email
  expose :phone
end

defmodule MailingAddress do
  use Maru.Entity
  extend UserData, only: [
    address: [:address1, :address2]
  ]
end

defmodule BasicInfomation do
  use Maru.Entity
  extend UserData, except: [:address]
end

Specs

parse(Keyword.t()) :: Maru.Entity.Struct.Exposure.t()