This project is archived and is in readonly mode.

#6065 ✓resolved
Robert Pankowecki

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

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

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.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Referenced by

Pages