Skip to content

Add callbacks to models dynamically #5436

Answered by alexbevi
jeffsaremi asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @jeffsaremi, as Mongoid has a dependency on ActiveModel, which in turn depends on ActiveSupport we can use an ActiveSupport::Concern similar to the following:

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 Mon…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@jeffsaremi
Comment options

@alexbevi
Comment options

Answer selected by alexbevi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants