Skip to content

Hi Mongoid community, when a Mongoid object is updated( e.g. save operation), is there an easy way to track(via code) all other Mongoid objects that might be accessed? #5835

Closed Answered by jamis
d2army asked this question in Q&A
Discussion options

You must be logged in to vote

Hey @d2army, there's not really a built-in way to do this, but here's a quick-and-dirty proof-of-concept I threw together. Maybe it'll give you some ideas?

module SaveTracking
  extend ActiveSupport::Concern

  class <<self
    def apply!
      Mongoid.models.each { |klass| klass.include(SaveTracking) }
      reset!
    end

    def reset!
      @touched_classes_map = nil
    end

    def touched_classes_map
      @touched_classes_map ||= Hash.new(0)
    end

    def track_save!(model)
      touched_classes_map[model.class] += 1
    end

    def around
      reset!
      yield
      touched_classes_map
    end
  end

  included do
    before_save { SaveTracking.track_save!(self) }
  end
end

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by d2army
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