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.
How about putting it in your config/initializers/constants.rb?
That ensure that it will only be called once on app start
just put
USER = Role.find_by_key('user')
ADMIN = Role.find_by_key('admin')
and you can use the USER/ADMIN constant in your app
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.