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.

after_initialize callback included from a module isn't fired

#5448

In Rails 2.3, it was possible to define an after_initialize callback in a module that was included into a model class:

module UserCallbacks
  def after_initialize
    puts "after_initialize"
  end
end

class User < ActiveRecord::Base
  include UserCallbacks
end

The method was called as expected when creating a new instance of the model.

However, in Rails 3 (RC2) this doesn't happen. It's not very conducive to DRYing up my models that have common behavior.

Reported by Pete Deffendol · August 24th, 2010 @ 06:25 PM

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

Activity

  1. Pete Deffendol
    Pete Deffendol

    After some experimentation, the following produces the desired result, although I still do not know why the original sample would fail:

    module Common
      class Callbacks
        def self.after_initialize(record)
          puts "after_initialize"
        end
      end
      
      def self.included(base)
        base.instance_eval do
          after_initialize Callbacks
        end
      end
    end
    
    class User < ActiveRecord::Base
      include Common
    end
    

    I was under the impression, that "for performance reasons," only the explicit definition of "after_initialize" was allowed. The above use of the callback class seems to contradict that. Perhaps I am reading the documentation incorrectly? (http://edgeguides.rubyonrails.org/active_record_validations_callbac...)

    August 24th, 2010 @ 09:05 PM

  2. José Valim
    José Valim
    • State changed from new to wontfix
    • Importance changed from to Low

    In Rails 3, calling methods with the same name as the callback was deprecated. That said, you need to something like this:

    module UserCallbacks
      def self.included(base)
        base.after_initializer :some_method
      end
      def some_method
        #
      end
     end
    

    August 25th, 2010 @ 02:54 AM

  3. Pete Deffendol
    Pete Deffendol

    That's good to know, however, it looks like the documentation needs to be updated. Looking at http://github.com/rails/rails/blob/master/activerecord/lib/active_r... the part about an explicit implementation is misleading if not plain wrong.

    August 25th, 2010 @ 05:49 PM

  4. Rohit Arondekar
    Rohit Arondekar

    Pete, if you would like to do it, the API Docs and the Guides can be edited here http://github.com/lifo/docrails You'll have to ask lifo (on Github) for write permissions and then you can edit the docs. The changes will be merged with the main Rails repo later on.

    August 26th, 2010 @ 01:34 AM