Skip to content

Instantly share code, notes, and snippets.

@jnraine
Created July 11, 2011 00:11
Show Gist options
  • Save jnraine/1075117 to your computer and use it in GitHub Desktop.
Save jnraine/1075117 to your computer and use it in GitHub Desktop.
An early version of a Rails settings model
class Setting < ActiveRecord::Base
@@settings = {}
belongs_to :record, :polymorphic => true
validates_uniqueness_of :key
before_save :expire_cache
# Retrieve and cache a value for a key
def self.retrieve_value(key)
record = find_by_key(key) if @@settings[key].nil?
@@settings[key] ||= record.value if record.present?
@@settings[key]
end
# Expire settings cache
def self.expire_cache
@@settings = {}
end
def expire_cache
self.class.expire_cache
end
def self.cache
@@settings
end
# Obtain the value from a key. If no record exists, return
# nil.
def self.find_by_key(key)
self.where(:key => key).first
end
private
# Yikes, this is getting unruley
def self.method_missing(method_id, *arguments, &block)
# Setup a counter to avoid annoying recursion
@mm_counter ||= 0
@mm_counter += 1
if @mm_counter > 1
@mm_counter = 0
super
else
value = retrieve_value(method_id)
if value.nil?
@mm_counter = 0
super
else
@mm_counter = 0
value
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment