Reputation: 92387
I have a Rails model class like this:
class Something < ActiveRecord::Base
before_create do
self.key = SecureRandom.urlsafe_base64(8)
end
end
Why can I call before_create
here? I expected it to be a method of ActiveRecord::Base
but it is not. Callbacks are methods of ActiveRecord::Callbacks
. But why can I call them in a model class without including something?
Upvotes: 2
Views: 325
Reputation: 8834
Callbacks are a Module within ActiveRecord that Module is then 'mixed in' to Base which 'Something' extends. Modules/Mixins are kind of like interfaces in some static languages but they also include the implementation of a method rather than just a contract to implement it.
Upvotes: 1
Reputation: 20724
Because ActiveRecord::Base includes it for you. See https://github.com/rails/rails/blob/master/activerecord/lib/active_record/base.rb#L2135
Upvotes: 2
Reputation: 434615
You can do that because ActiveRecord::Base
does this (or something similar depending on your version of Rails):
Base.class_eval do
#...
include Callbacks, ActiveModel::Observing, Timestamp
#...
end
So ActiveRecord::Base
already includes ActiveRecord::Callbacks
and your class picks up the callbacks by inheriting from ActiveRecord::Base
.
Upvotes: 3