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
Link to this section Functions
Specs
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 Map.get and options.
- Expose a field or a set of fields with custom function without options.
Expose a field or a set of fields with custom function and options.
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()