Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2751

Atomic updates should invoke callbacks

    XMLWordPrintable

    Details

    • Type: Task
    • Status: Closed
    • Resolution: Done
    • Affects Version/s: None
    • Fix Version/s: 4.0.0 final
    • Component/s: None
    • Labels:
      None

      Description

      It could have been like this by design, but it's pretty common to want to invoke callbacks for atomic updates. A valid scenario is invalidating a cache (see https://github.com/dblock/mongoid-cached-json/issues/7).

      If not invoking before_save/update on an inc is by design, maybe there should be a built-in callback for inc or similar atomic operations?

      require 'spec_helper'
       
      class Gadget
        include Mongoid::Document
       
        field :count, type: Integer
        before_update :called
        before_save :called
       
        def callback_count
          @callback_count
        end
       
        def called
          @callback_count = @callback_count.to_i + 1
        end
      end
       
      describe "inc" do
        it "calls the callback" do
          gadget = Gadget.create!
          gadget.callback_count.should == 1 # before_save
          gadget.update_attributes!({ count: 10 })
          gadget.callback_count.should == 3 # before save and update
          gadget.inc(:count, 1)
          gadget.callback_count.should == 4
        end
      end
      

        Attachments

          Activity

            People

            • Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: