Application Settings through ActiveRecord
After a few side projects I’ve noticed that I’d use this approach for a settings object pretty often. My settings table is very basic, just two columns, name and value. The magic happens inside the Settings model.
# app/model/settings.rb class Settings < ActiveRecord::Base class << self def setup return if @settings @settings = {} all.each { |s| @settings[s.name.to_sym] = s.value } end def [](key) setup @settings[key] end end end
I gave myself a setup method that cycles through every entry in my settings table and stores them in the @settings hash. Notice I call return if @settings is defined because there’s no need in rebuilding @settings. Next, I define the [] method to make the model act like a hash. Inside the [] method I return the value @settings at the position of the provided key.
It allows me to do stuff like this:
puts Settings[:name] puts Settings[:version]
It’s really simple, but I like it. What about you?
Comments
Comments have been closed.