I have defined an after_initialize and a after_find callback in my User model as such:
Please, assume that my User has an attribute named email too.
class User < ApplicationRecord
after_initialize do |user|
puts "You have initialized an object! Email: #{email}"
end
after_find do |user|
puts "You have found an object! Email: #{email}"
end
end
following the documentation that I've found in the Rails Guides.
This works as expected. I.e. when I call User.new or User.first I see the output being printed as expected:
2.3.3 :001 > User.new(email: 'foo@gmail.com')
You have initialized an object! Email: foo@gmail.com
=> #<User id: nil, email: "foo@gmail.com", password_digest: nil,
created_at: nil, updated_at: nil, email_confirmation_token: nil,
terms_of_service: false, country_id: nil>
2.3.3 :002 > User.first
User Load (0.6ms) SELECT "users".* FROM "users" ORDER BY "users"."id"
ASC LIMIT $1 [["LIMIT", 1]]
You have found an object! Email: mary@gmail.com
You have initialized an object! Email: mary@gmail.com
=> #<User id: 10, email: "mary@gmail.com", password_digest:
"$...", created_at: "2017-06-10 06:46:05", updated_at: "2017-07-02
09:52:46", email_confirmation_token: "yStnErkVCFC9mYNHKFNYdA",
terms_of_service: true, country_id: nil>
My question is why does the documentation of the callbacks mention the presence of the block local variable user? As you can see from what I have experienced above, the user local variable is not used, but I still have access to the User instance instantiated and/for found.