Sha256: 9f21de940ded2ac1db0eb8f842335ef854be9fb359fd799095e06b03dfec4812

Contents?: true

Size: 1.01 KB

Versions: 2

Compression:

Stored size: 1.01 KB

Contents

class Settings < ActiveRecord::Base
  validates_uniqueness_of :key
  after_save :clear_cache
  after_destroy :clear_cache

  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)
    if setting = find_cached(key)
      setting.value
    else
      nil
    end
  end
  
  def self.[]=(key, val)
    key = key.to_s
    setting = Settings.find_by_key(key) || Settings.new(:key => key)
    setting.value = val
    setting.save
  end
  
  def self.keys
    self.find(:all, :select => 'key', :order => 'key ASC').map{|s| s.key.to_sym}
  end
  
  def self.remove(key)
    key = key.to_s
    setting = Settings.find_by_key(key)
    if setting
      setting.destroy
    else
      nil
    end
  end
private
  def self.find_cached(key)
    key = key.to_s
    Rails.cache.fetch("settings/#{key}") { Settings.find_by_key(key) }
  end
  
  def clear_cache
    Rails.cache.delete("settings/#{key}")
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
settings-goo-0.2.0 lib/settings.rb
settings-goo-0.1.0 lib/settings.rb