0

Does ActiveSupport::Concern support a way to run a method before or after the object's constructed.

e.g. to achieve something like

Module Benchmarker

  extend ActiveSupport::Concern

  before_initialize
    @constructed_at = DateTime.now
  end

end

(Note: Not wanting this for ActiveRecord or ActiveController. Just a generic Ruby class within a Rails project.)

mahemoff
  • 44,526
  • 36
  • 160
  • 222

1 Answers1

3

NOTE: This would work for models or only those classes which inherit from ActiveRecord.

Rails does not support a before_initialize callback. You could use the after_initialize callback instead. However, when using it in a concern, you need to mention it in an included do..end block. For example, the following code should work for your use case:

Module Benchmarker
  extend ActiveSupport::Concern

  included do
    after_initialize do |subject|
      p "I'm in after_initialize"
    end
  end
end

You could refer to this answer for more details on how the included hook works.

Anuj Khandelwal
  • 1,214
  • 1
  • 8
  • 16
  • Where does this `after_initialize` come from? – Sergio Tulentsev Feb 20 '19 at 14:21
  • It is one of the callbacks provided by Rails. https://guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find The code in `after_initialize` gets triggered as soon as we instantiate an object. – Anuj Khandelwal Feb 20 '19 at 14:23
  • There's no such thing as "rails provides". Rails is a huge monster, consisting of many many smaller libs. Your link points to a page titled "Active Record callbacks". Note that active record is not mentioned in the question. If a class is not an activerecord (or does not include the relevant activemodel module), it does not get that callback. – Sergio Tulentsev Feb 20 '19 at 14:26
  • Well, Activesupport is mentioned in the question, and that is definitely part of Rails. Link: https://github.com/rails/rails/tree/master/activesupport Also, the question is tagged as a "Ruby on Rails" question. Hence, the usage of ActiveRecord is justified – Anuj Khandelwal Feb 20 '19 at 14:31
  • "the usage of ActiveRecord is justified" - no, it's not. Not every class in a rails app is an activerecord. Some rails apps don't even have activerecord loaded. And activesupport by itself doesn't offer these callbacks. – Sergio Tulentsev Feb 20 '19 at 14:32
  • 2
    Added a note mentioning the usage in only those classes that include ActiveRecord – Anuj Khandelwal Feb 20 '19 at 14:32
  • Yes, note is good, but, IMHO, it deserves a more prominent position. Like, at the very top, and in bold font :) – Sergio Tulentsev Feb 20 '19 at 14:35
  • Agreed! @SergioTulentsev – Anuj Khandelwal Feb 20 '19 at 14:37