Set constants through database

Dan Chak explained in his book Enterprise Rails, why domain data should be stored in database tables. Domain data don’t change frequently and normally not through an interaction with the application.

For example, domain data can be the roles of users.

Role.create(:key => 'user', :description => 'A normal user')
Role.create(:key => 'admin', :description => 'The admin of the page')

The role constants can be set in the following way (based on the example in Enterprise Rails, Chapter 7)

class Role < ActiveRecord::Base
  USER = Role.find_by_key('user')
  ADMIN = Role.find_by_key('admin')
end

Now you can use this constants like

my_user.role = Role::ADMIN

My solution is, to set the constants dynamicly

class Role < ActiveRecord::Base
  # set role contants like Role::ADMIN,..
  Role.all.each do |role|
    Role.const_set(role.key.upcase, role)
  end
end

The big advantage by setting a constant through the database is that the select query will be executed only once for a running application. If you restart the application, the constants will be refreshed.

Trackback

no comment untill now

Add your comment now

Switch to our mobile site