Attribute types
On top of the adapter's column-type coercion, models can declare a per-attribute type — a small casting layer that converts values at three points:
| Hook | Direction | When |
|---|---|---|
cast |
user input → Raku | build / assign-attributes |
deserialize |
DB value → Raku | reading a record from the DB |
serialize |
Raku → DB value | saving a record |
Declare types in the model's submethod BUILD, alongside associations and
scopes. Import the type system with use ORM::ActiveRecord::Type;.
Custom attribute types
A type is any object that does the AttributeType role. Override the hooks you
need (each defaults to identity; deserialize defaults to cast):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Serialized columns
serialize stores a structured Raku value in a text column through a coder.
JsonCoder is built in; any object with .dump / .load works as a custom
coder:
1 2 3 4 5 6 7 8 | |
YamlCoder stores the value as YAML; import it from
ORM::ActiveRecord::Type::Yaml:
1 2 3 | |
A custom coder is any object with .dump($value) (Raku → string) and
.load($string) (string → Raku):
1 2 3 4 5 6 | |
Store accessors
store serializes a column and exposes named accessors that read and write
keys inside the stored hash. It defaults to JsonCoder; pass coder for
another:
1 2 3 4 5 6 7 8 9 10 | |
store-accessor adds accessors to an already-serialized column after the fact:
1 2 | |
Defaults
attribute takes a default — a plain value or a block evaluated per new
record. The default applies only when the attribute is not supplied:
1 2 3 4 5 6 7 8 9 | |
Overriding a column's type
When the attribute name matches a column, the declared type replaces the
adapter's default coercion for that column (the CsvType example above
overrides a text column). Everything else about the column is unchanged.
Virtual attributes
An attribute whose name matches no column is virtual: it is read, written,
typed, and defaulted like any other attribute, but it is left out of every
INSERT and UPDATE. Use it for derived or transient state.
1 2 3 4 5 6 7 8 9 | |
The type registry
Built-in types are registered under names (integer, string, boolean,
float, decimal, datetime). Register your own and reference it by name:
1 2 3 4 5 | |