base.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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_by_startup
  14. return @cache_prefix_by_startup if defined? @cache_prefix_by_startup
  15. return '' unless Default.enabled?
  16. @cache_prefix_by_startup = Digest::MD5.hexdigest(Default.instance.to_s)
  17. end
  18. def cache_prefix(&block)
  19. @cache_prefix = block
  20. end
  21. def cache_key(var_name, scope_object)
  22. scope = ['rails_settings_cached', cache_prefix_by_startup]
  23. scope << @cache_prefix.call if @cache_prefix
  24. scope << "#{scope_object.class.name}-#{scope_object.id}" if scope_object
  25. scope << var_name.to_s
  26. scope.join('/')
  27. end
  28. def [](key)
  29. return super(key) unless rails_initialized?
  30. val = Rails.cache.fetch(cache_key(key, @object)) do
  31. super(key)
  32. end
  33. val
  34. end
  35. # set a setting value by [] notation
  36. def []=(var_name, value)
  37. super
  38. Rails.cache.write(cache_key(var_name, @object), value)
  39. value
  40. end
  41. def save_default(key, value)
  42. Kernel.warn 'DEPRECATION WARNING: RailsSettings save_default is deprecated ' \
  43. 'and it will removed in 0.7.0. ' \
  44. 'Please use YAML file for default setting.'
  45. return false unless self[key].nil?
  46. self[key] = value
  47. end
  48. end
  49. end
  50. end