annotation Athena::ORM::Annotations::PrePersist
#
Marks a method to be called when a new entity is persisted, before it's inserted.
It runs once per entity, whether it's persisted via AORM::EntityManager#persist, a "persist" cascade, or found through such a cascade when flushing.
@[AORMA::Entity]
class User < AORM::Entity
# ...
@[AORMA::Column]
property! created_at : Time
@[AORMA::PrePersist]
def set_created_at : Nil
@created_at = Time.utc
end
end
Lifecycle Callbacks#
Lifecycle callbacks are public instance methods of the entity, annotated with the event they run for. They're best used for simple operations specific to the entity, such as setting timestamps.
A callback either has no parameters, or one parameter restricted to the event's type, which gives access to the entity manager:
@[AORMA::PrePersist]
def set_created_at(event : AORM::Events::PrePersistEventArgs(User)) : Nil
event.entity_manager # => AORM::EntityManager
end
Any other signature is a compile-time error. An entity may have more than one callback for the same event, and a method may have more than one callback annotation.
Callbacks declared in a module, or in an abstract parent class, apply to every entity that includes or inherits from it, see Sharing Mapped Properties. Overriding such a method in the entity without the annotation removes the callback.
Note
Callbacks only run for the entity they're declared on. Listening to an event for every entity isn't supported yet.