module Avram::Callbacks

Direct including types

Defined in:

avram/callbacks.cr

Macro Summary

Macro Detail

macro after_commit(method_name) #

Run the given method after save and after successful transaction commit

The newly saved record will be passed to the method.

class SaveComment < Comment::SaveOperation
  after_commit notify_post_author

  private def notify_post_author(comment : Comment)
    NewCommentNotificationEmail.new(comment, to: comment.author!).deliver_now
  end
end

[View source]
macro after_save(method_name) #

Run the given method after save, but before transaction is committed

This is a great place to do other database saves because if something goes wrong the whole transaction would be rolled back.

The newly saved record will be passed to the method.

class SaveComment < Comment::SaveOperation
  after_save touch_post

  private def touch_post(comment : Comment)
    SavePost.update!(comment.post!, updated_at: Time.utc)
  end
end

This is not a good place to do things like send messages, enqueue background jobs, or charge payments. Since the transaction could be rolled back the record may not be persisted to the database. Instead use after_commit


[View source]
macro before_save(method_name) #

Run the given method before saving or creating

This runs before saving and before the database transaction is started. You can set defaults, validate, or perform any other setup necessary for saving.

before_save run_validations

private def run_validations
  validate_required name, age
end

[View source]
macro before_save #

Run the given block before saving or creating

This runs before saving and before the database transaction is started. You can set defaults, validate, or perform any other setup necessary for saving.

before_save do
  validate_required name, age
end

[View source]