Guest User

Untitled

a guest
Jul 17th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. ## model
  2. class Configuration < ActiveRecord::Base
  3. class KeyNotFound < RuntimeError; end
  4.  
  5. after_update :clear_cache
  6.  
  7. # Reads config values. `Config["the_key"]`
  8. def self.[](key)
  9. Rails.cache.read("config::#{key}") || store_in_cache(key)
  10. end
  11.  
  12. def self.store_in_cache(key)
  13. found_key = find_by_key(key)
  14.  
  15. if found_key
  16. Rails.cache.write("config::#{key}", found_key.value)
  17. return Rails.cache.read("config::#{key}")
  18. else
  19. raise KeyNotFound, "Configuration key `#{key}' was not found."
  20. end
  21. end
  22.  
  23. private
  24.  
  25. def clear_cache
  26. Rails.cache.write("config:#{self.key}", nil)
  27. end
  28. end
  29.  
  30. ## test
  31. require 'test_helper'
  32.  
  33. class ConfigurationTest < ActiveSupport::TestCase
  34. def setup
  35. Rails.cache.clear
  36. end
  37.  
  38. test "reading directly from cache" do
  39. Rails.cache.write("config::foo", 5)
  40. Configuration.expects(:store_in_cache).never
  41. assert_equal 5, Configuration["foo"]
  42. end
  43.  
  44. test "reading from db, storing in cache, and reading from cache" do
  45. Factory(:configuration, :key => "foo", :value => 5)
  46. assert_equal 5, Configuration["foo"]
  47. end
  48.  
  49. test "key not in db" do
  50. assert_raises(Configuration::KeyNotFound) { Configuration["foo"] }
  51. end
  52. end
Add Comment
Please, Sign In to add comment