Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveRecord::Observer is not aware of method added by including modules

#6065

This implementation works"

class RequestObserver < ActiveRecord::Observer
 def after_commit(o)
  # do something
 end
end

however this one not:

class RequestObserver < ActiveRecord::Observer

  module A
    def after_commit(o)
      # do sth
    end
  end

  include A
end

You need to do it this way:

class RequestObserver < ActiveRecord::Observer
  module A
    def after_commit(o)
      # do sth
    end
  end

  include A
  self.observed_methods += [:after_commit]
  self.observed_methods.freeze
end

This is because of current implementation of the observer class:

def self.method_added(method)
  method = method.to_sym

  if ActiveRecord::Callbacks::CALLBACKS.include?(method)
    self.observed_methods += [method]
    self.observed_methods.freeze
  end
end

It is not mentioned in the documentation, nor intuitive.

Couldn't we just check respond_to? result to know what the observer is capable of instead of keeping the list in observed_methods field?

I can understand that adding new methods to the observer later dynamically is not supported because of performance reason but not supporting primary Ruby construction is a shame.

BTW: Here is my concept: let ActiveRecord::Observer have included an module with all callbacks methods defined as empty methods
We wouldn't have to worry about the methods existence and could just call them. Writing a method in the observer or including another module would overwrite them.

Reported by Robert Pankowecki · November 25th, 2010 @ 05:01 PM

State: resolved
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Neeraj Singh
    Neeraj Singh
    • Importance changed from to Low

    Can you submit a patch with what you think should be the behavior. Thanks.

    November 25th, 2010 @ 10:25 PM

  2. Robert Pankowecki
    Robert Pankowecki
    • Tag changed from activerecord, module, observed_methods, observers, rails3, rails3.0.3 to activerecord, module, observed_methods, observers, patch, rails3, rails3.0.3

    I made the implementation much simpler.

    November 26th, 2010 @ 06:22 PM

  3. Robert Pankowecki
  4. Robert Pankowecki
    Robert Pankowecki

    Do you think the patch is fine ?

    November 28th, 2010 @ 09:43 PM

  5. lewy313
    lewy313

    I checked this patch today and it worked for me

    December 9th, 2010 @ 09:22 AM

  6. Aaron Patterson
    Aaron Patterson

    sigh. Why didn't observers work like this in the first place?

    This patch is fine and I'll apply.

    December 9th, 2010 @ 06:39 PM

  7. Repository
  8. Repository