Skip to content

Instantly share code, notes, and snippets.

@skiz
Created May 7, 2010 17:48
Show Gist options
  • Save skiz/393769 to your computer and use it in GitHub Desktop.
Save skiz/393769 to your computer and use it in GitHub Desktop.
class CreateConfigurations < ActiveRecord::Migration
def self.up
create_table :configurations do |t|
t.string :key
t.text :value
t.timestamps
end
add_index :configurations, :key, :unique => true
end
def self.down
remove_index :configurations, :key, :unique => true
drop_table :configurations
end
end
class Configuration < ActiveRecord::Base
serialize :value
validates_uniqueness_of :key
class << self
def get(key)
Rails.cache.fetch("Config.#{key}") {
find_by_key(key.to_s).try(:value)
}
end
def set(key, value)
c = find_or_initialize_by_key(key.to_s)
c.update_attribute(:value, value)
Rails.cache.write("Config.#{key}", value)
end
alias :defined? :get
alias :[]= :set
alias :[] :get
end
end
require 'test_helper'
class ConfigurationTest < ActiveSupport::TestCase
test "setting a string configuration" do
Configuration.set(:a_str, 'This is a string')
assert Configuration.get(:a_str).is_a?(String)
assert_equal 'This is a string', Configuration.get(:a_str)
end
test "setting an integer configuration" do
Configuration.set(:an_int, 42)
assert Configuration.get(:an_int).is_a?(Integer)
assert_equal 42, Configuration.get(:an_int)
end
test "setting any other marshalable object" do
Configuration.set(:anything, {:hash => 'works too'})
assert Configuration.get(:anything).is_a?(Hash)
end
test "retrieving non-existant key should be nil" do
assert_nil Configuration.get(:dont_exist)
end
test "additional alias for defined?" do
assert Configuration.respond_to?(:defined?)
end
test "caching support" do
Rails.cache.write('Config.foo', 'blah')
assert_equal 'blah', Configuration.get('foo')
end
test "key based support" do
Configuration['test'] = 'example'
assert_equal 'example', Configuration['test']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment