Sha256: 4c4f18591b233be212050dfe3706d6ee97487efce31fb3a8a66ebe0e7f8cbf47

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 KB

Contents

class Settings < ActiveRecord::Base
  validates_presence_of :key
  validates_uniqueness_of :key
  after_save :clear_cache
  after_create :clear_cache_keys
  #TODO - Only clear cached keys when :key is updated, not :value
  after_update :clear_cache_keys
  after_destroy :clear_cache
  after_destroy :clear_cache_keys

  def value
    val = self[:value]
    if val
      ActiveSupport::JSON.decode val
    else
      nil
    end
  end
  
  def value=(val)
    self[:value] = val.to_json
  end
    
  def self.[](key)
    setting = find_cached(key)
    if setting
      setting.value
    else
      nil
    end
  end
  
  def self.[]=(key, val)
    return nil if key.blank?
    setting = Settings.find_key(key.to_s)
    setting.update_attribute(:value, val) if setting
  end
  
  def self.keys
    Rails.cache.fetch("settings/settings.keys") {
      self.find(:all, :select => 'key', :order => 'key ASC').map{|setting| setting.key.to_sym}
    }
  end
  
  def self.remove(key)
    Settings.destroy_all(:key => key.to_s).first
  end
private
  def self.find_key(key)
    key = key.to_s
    Settings.find_by_key(key) || Settings.new(:key => key)
  end

  def self.find_cached(key)
    Rails.cache.fetch("settings/#{key}") { Settings.find_by_key(key.to_s) }
  end
  
  def clear_cache
    Rails.cache.delete("settings/#{key}")
  end
  
  def clear_cache_keys
    Rails.cache.delete("settings/settings.keys")
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
settings-goo-0.3.4 lib/settings.rb
settings-goo-0.3.2 lib/settings.rb