Deriving Values
Some new requirements for our app have come in:
We want to anonymize admins even further. Their name should be of the form "Admin-X" where 'X' is the admin users id
Each post should contain the name of its author
(both of these are bad ideas, but office politics forces you to accept them)
Function 'directives' (see Directives 101) won't really help us here since they don't have access to the entity being built. We need a new directive, derive
:
derive
allows us to, well, derive values from either keys on the same entity or from any dependent entities created using one
(or other similar directives). Its first argument can be a key or a path - i.e. it identifies the entity or key to be derived from - the second is a function that's used to transform the source value into the derived value.
We'll go into more detail on paths later, for now it's enough to know that a path is a sequence of one or more keywords. Our path in the post factory is [:author]
which can be translated to 'derive a value from the entity referenced through the author key', and we're using :name
as the transform function to get the author's name.
Let's see this in action on the user entity first:
The derived value responds to changes in the value of the underlying key - if we specify the ID it gets reflected in the user's name. If we specify the name as a string the derive
has no effect.
Now for the post factory:
As before: if we change the name of the author user, we change the value of the author-name key. Now let's try:
There are a few things to unpack here:
The
derive
directive works happily in a:with
optionIf we derive from the keyword
:author
instead of a path[:author]
, we derive from the value of that key on the post entity we build - in this case the id of the author entityWe can derive multiple values from the same dependent entity
Last updated