cache.rb 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. Rails.logger.error e
  28. end
  29. end
  30. =begin
  31. get a cache
  32. value = Cache.get('some_key')
  33. =end
  34. def self.get(key)
  35. Rails.cache.read(key.to_s)
  36. end
  37. =begin
  38. clear whole cache store
  39. Cache.clear
  40. =end
  41. def self.clear
  42. # workaround, set test cache before clear whole cache, Rails.cache.clear complains about not existing cache dir
  43. Cache.write('test', 1)
  44. Rails.cache.clear
  45. end
  46. end