Add callbacks to models dynamically #5436
-
Is there a way to add callbacks such as "before_save" and such dynamically to all models before they 're actually used. This would be useful for tracing calls and object creation sequences.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @jeffsaremi, as Mongoid has a dependency on module TracingExtension
extend ActiveSupport::Concern
included do
[:after_initialize, :before_create, :before_save, :before_update, :after_create, :after_save, :after_update].each do |callback|
self.send(callback, proc { trace_callback(callback) })
end
protected
def trace_callback(sym)
puts ">>>#{self.class.name} #{sym}"
end
end
end Using the above concern we can run a test with 2 models such as the following, which should trigger the associated callbacks as desired: class Post
include Mongoid::Document
field :title, type: String
end
class User
include Mongoid::Document
field :name, type: String
end
Mongoid.models.each do |model|
model.send(:include, TracingExtension)
end
Post.create! title: "My First Post"
u = User.new name: "Test"
u.save!
u.name = "Test2"
u.save! Output:
|
Beta Was this translation helpful? Give feedback.
Hi @jeffsaremi, as Mongoid has a dependency on
ActiveModel
, which in turn depends onActiveSupport
we can use anActiveSupport::Concern
similar to the following:Using the above concern we can run a test with 2 models such as the following, which should trigger the associated callbacks as desired: