Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## model
- class Configuration < ActiveRecord::Base
- class KeyNotFound < RuntimeError; end
- after_update :clear_cache
- # Reads config values. `Config["the_key"]`
- def self.[](key)
- Rails.cache.read("config::#{key}") || store_in_cache(key)
- end
- def self.store_in_cache(key)
- found_key = find_by_key(key)
- if found_key
- Rails.cache.write("config::#{key}", found_key.value)
- return Rails.cache.read("config::#{key}")
- else
- raise KeyNotFound, "Configuration key `#{key}' was not found."
- end
- end
- private
- def clear_cache
- Rails.cache.write("config:#{self.key}", nil)
- end
- end
- ## test
- require 'test_helper'
- class ConfigurationTest < ActiveSupport::TestCase
- def setup
- Rails.cache.clear
- end
- test "reading directly from cache" do
- Rails.cache.write("config::foo", 5)
- Configuration.expects(:store_in_cache).never
- assert_equal 5, Configuration["foo"]
- end
- test "reading from db, storing in cache, and reading from cache" do
- Factory(:configuration, :key => "foo", :value => 5)
- assert_equal 5, Configuration["foo"]
- end
- test "key not in db" do
- assert_raises(Configuration::KeyNotFound) { Configuration["foo"] }
- end
- end
Add Comment
Please, Sign In to add comment