Hi!
In the Rails app I'm developing I have some data stored in the database
that acts like constants. For example, I populate a profiles table with all
the profile types using seeds.rb. To avoid hardcoding the profile ids in my
code, everytime I needed to do an operation involving a profile type I
first retrieved the profile type from the database:
<code>
admin = Profile.find_by_name('admin')
@all_admins = admin.people
</code>
Since the profile ids (and other 'constants' stored in the database) can
only change if the sys admin changes their values before the deploy
(editing seeds.rb), I though of using initializers to retrieve references
to all those database constants (therefore opening less connections with
the database during application usage):
in .../initializers/
<code>
class DatabaseConstants < ActiveRecord::Base
# loading the profiles
temp_profiles = {}
Profile.all.each do |profile|
case profile.name
when 'foo'
temp_profiles[:foo] = profile
when 'bar'
temp_profiles[:bar] = profile
when 'admin'
temp_profiles[:admin] = profile
when 'super-admin'
temp_profiles[:super_admin] = profile
end
end
PROFILES = temp_profiles
# other 'constants' to be loaded
# ...
end
</code>
and then, I can do something like the following in a controller:
<code>
@all_admins = DatabaseConstants::PROFILES[:admin].people
</code>
I have tested this solution and it works perfectly fine. However, I would
like to know from veteran Rails developers if this is a good (or
acceptable) use of initializers (and if this should really increase
performance).
Cheers,
Alex.
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
To view this discussion on the web visit
https://groups.google.com/d/msg/rubyonrails-talk/-/bmtvpHG8CykJ.
For more options, visit https://groups.google.com/groups/opt_out.