ruby 关于服务缓存的冥想,带有一个示例stroage类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 关于服务缓存的冥想,带有一个示例stroage类相关的知识,希望对你有一定的参考价值。

require 'securerandom'

class JsonFileCache
  def initialize(path = nil)
    @path = path || "/tmp/cache/#{SecureRandom.uuid}" # safe default
  end

  # Retrieves whole cache or single record if key is provided
  def get(key = nil)
    @cache ||= load_file

    key ? @cache[key] : @cache
  end

  # Sets or resets a key valua and writes to storage
  def set(key, data)
    @cache[key] = data
    write
    data
  end

  private

  def write
    File.write(@path, JSON.dump(@cache))
  end

  def load_file
    JSON.parse(File.read(@path))
  end
end
# Examples:
# cache = JsonFileCache.new("tmp/cache/geolocation.json")
# $geolocation = ServiceCache.new(GeolocalateUser, cache)
#
# ll = $geolocation.get(User.last)
# => { lat: 3.0, lng: 40.1 } # calling API
#
# ll = $geolocation.get(User.last)
# => { lat: 3.0, lng: 40.1 } # reading file
#
# Requirements:
# object:  must respond to 'id'
# service: must respond to 'call' with one argument
# cache:   must respond to get(key) and set(key, response)
# cache.set() must be complatible with service.call response type
class ServiceCache
  def initialize(service:, cache:)
    @service = service
    @cache   = cache
  end

  def get(object)
    cache_read(object) || service_call(object)
  end

  private

  def cache_read(object)
    @cache.get(object.id)
  end

  def service_call(object)
    response = @service.call(object)
    @cache.set(object.id, response) # set() returns 'response'
  end
end 

以上是关于ruby 关于服务缓存的冥想,带有一个示例stroage类的主要内容,如果未能解决你的问题,请参考以下文章

ruby 对Sandi Metz的“Make Everything the same”博客文章进行冥想

ruby 作为对https://practicingruby.com/articles/meditations-on-bad-and-good-code-1 artice的冥想,这是我第一次尝试重构

关于大脑休息之睡觉与冥想方式对比

转:关于管理的十大冥想

转:关于管理的十大冥想

谁负责从带有缓存的 Flux 应用程序中的服务器获取数据?