base.rb 1005 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. module RailsSettings
  2. class Base < Settings
  3. def rewrite_cache
  4. Rails.cache.write(cache_key, value)
  5. end
  6. def expire_cache
  7. Rails.cache.delete(cache_key)
  8. end
  9. def cache_key
  10. self.class.cache_key(var, thing)
  11. end
  12. class << self
  13. def cache_prefix(&block)
  14. @cache_prefix = block
  15. end
  16. def cache_key(var_name, scope_object)
  17. scope = ["rails_settings_cached"]
  18. scope << @cache_prefix.call if @cache_prefix
  19. scope << "#{scope_object.class.name}-#{scope_object.id}" if scope_object
  20. scope << var_name.to_s
  21. scope.join("/")
  22. end
  23. def [](key)
  24. return super(key) unless rails_initialized?
  25. val = Rails.cache.fetch(cache_key(key, @object)) do
  26. super(key)
  27. end
  28. val
  29. end
  30. # set a setting value by [] notation
  31. def []=(var_name, value)
  32. super
  33. Rails.cache.write(cache_key(var_name, @object), value)
  34. value
  35. end
  36. end
  37. end
  38. end