Create a gist now

Instantly share code, notes, and snippets.

Mongoid Callback Sequence
require 'rubygems'
require 'bundler/setup'
require 'mongoid'
Mongoid.configure do |config|
config.master = Mongo::Connection.new('localhost', 27017, :logger => nil).db('mongoid-test')
end
class A
include Mongoid::Document
field :a
before_save { p 'before_save' }
before_update { p 'before_update' }
before_create { p 'before_create' }
after_save { p 'after_save' }
after_update { p 'after_update' }
after_create { p 'after_create' }
around_save { |&b| p 'start around_save'; b.call; p 'end around_save' }
around_create { |&b| p 'start around_create'; b.call; p 'end around_create' }
around_update { |&b| p 'start around_update'; b.call; p 'end around_update' }
end
a = A.new
a.save
#=> "before_save"
#=> "start around_save"
#=> "before_create"
#=> "start around_create"
#=> "end around_create"
#=> "after_create"
#=> "end around_save"
#=> "after_save"
a.a = 1
a.save
#=> "before_save"
#=> "start around_save"
#=> "before_update"
#=> "start around_update"
#=> "end around_update"
#=> "after_update"
#=> "end around_save"
#=> "after_save"
@vasilakisfil

Mongoid 5.0.1 version:

require 'rubygems'
require 'bundler/setup'
require 'mongoid'

Mongoid.load!("config/mongoid.yml", :development)

Mongoid.logger.level = Logger::INFO
Mongo::Logger.logger.level = Logger::INFO

class A
  include Mongoid::Document
  field :a
  before_save   { p 'before_save' }
  before_update { p 'before_update' }
  before_create { p 'before_create' }
  after_save    { p 'after_save' }
  after_update  { p 'after_update' }
  after_create  { p 'after_create' }
  around_save   { |a, b| p 'start around_save';   b.call; p 'end around_save' }
  around_create { |a, b| p 'start around_create'; b.call; p 'end around_create' }
  around_update { |a, b| p 'start around_update'; b.call; p 'end around_update' }
  around_destroy { |a, b| p 'start around_update'; b.call; p 'end around_destroy' }
  after_destroy { p 'after_destroy' }
end

a = A.new
a.save

puts

a.a = 1
a.save

puts

a.destroy!
"before_save"
"start around_save"
"before_create"
"start around_create"
"end around_create"
"after_create"
"end around_save"
"after_save"

"before_save"
"start around_save"
"before_update"
"start around_update"
"end around_update"
"after_update"
"end around_save"
"after_save"

"start around_destroy"
"end around_destroy"
"after_destroy"
@contentfree

And what does A.create do? Does it skip the before_save? ('cause that's what I'm running into…)

@omouse
omouse commented Oct 21, 2016

wondering where before_validation fits into this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment