I have a question about setting up constants in Rails project.
From Dan Chak’s Enterprise Rails book, he explains that constant lookup code like below gets executed only once when the app starts. However, looking at the log, I think it gets run every time I use the constant.
class Role < ActiveRecord::Base
USER = Role.find_by_key('user')
ADMIN = Role.find_by_key('admin')
end
This definitely allows cleaner code as I can do something like:
current_user.role = Role::ADMIN
As an alternative, I read about ActiveSupport::Memoizable, but I want to confirm this setup results in multiple db lookup before changing my code around.
Thanks for your input!
That code will only get executed once each time your environment is loaded. This will happen often in development and test environments, but only once each time an app server is spawned in production.