cache.rb 1022 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module Cache
  2. =begin
  3. delete a cache
  4. Cache.delete('some_key')
  5. =end
  6. def self.delete(key)
  7. Rails.cache.delete(key.to_s)
  8. end
  9. =begin
  10. write a cache
  11. Cache.write(
  12. 'some_key',
  13. { some: { data: { 'structure' } } },
  14. { expires_in: 24.hours, # optional, default 7 days }
  15. )
  16. =end
  17. def self.write(key, data, params = {})
  18. if !params[:expires_in]
  19. params[:expires_in] = 7.days
  20. end
  21. # in certain cases, caches are deleted by other thread at same
  22. # time, just log it
  23. begin
  24. Rails.cache.write(key.to_s, data, params)
  25. rescue => e
  26. Rails.logger.error "Can't write cache #{key}: #{e.inspect}"
  27. end
  28. end
  29. =begin
  30. get a cache
  31. value = Cache.get('some_key')
  32. =end
  33. def self.get(key)
  34. Rails.cache.read(key.to_s)
  35. end
  36. =begin
  37. clear whole cache store
  38. Cache.clear
  39. =end
  40. def self.clear
  41. # workaround, set test cache before clear whole cache, Rails.cache.clear complains about not existing cache dir
  42. Cache.write('test', 1)
  43. Rails.cache.clear
  44. end
  45. end