Skip to content

Instantly share code, notes, and snippets.

@douglaslise
Forked from jingoro/gist:3015664
Last active July 31, 2018 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglaslise/ea992fcca7547ac2c5bde8f81e928cbc to your computer and use it in GitHub Desktop.
Save douglaslise/ea992fcca7547ac2c5bde8f81e928cbc to your computer and use it in GitHub Desktop.
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' }
after_build { p 'after_build' }
after_initialize { p 'after_initialize' }
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment