request_cache.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. module RailsSettings
  2. module RequestCacheGetter
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def enable!
  6. Thread.current[:rails_settings_request_cache_enable] = true
  7. end
  8. def disable!
  9. Thread.current[:rails_settings_request_cache_enable] = nil
  10. end
  11. def enabled?
  12. Thread.current[:rails_settings_request_cache_enable]
  13. end
  14. def all_settings
  15. enabled? ? settings : nil
  16. end
  17. def all_settings=(val)
  18. self.settings = val
  19. end
  20. end
  21. end
  22. if defined? ActiveSupport::CurrentAttributes
  23. # For storage all settings in Current, it will reset after per request completed.
  24. # Base on ActiveSupport::CurrentAttributes
  25. # https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html
  26. class RequestCache < ActiveSupport::CurrentAttributes
  27. include RequestCacheGetter
  28. attribute :settings
  29. end
  30. else
  31. # https://github.com/steveklabnik/request_store
  32. # For Rails 5.0
  33. require "request_store"
  34. class RequestCache
  35. include RequestCacheGetter
  36. class << self
  37. def reset
  38. self.settings = nil
  39. end
  40. def settings
  41. RequestStore.store[:rails_settings_all_settings]
  42. end
  43. def settings=(val)
  44. RequestStore.store[:rails_settings_all_settings] = val
  45. end
  46. end
  47. end
  48. end
  49. end