【问题标题】:How do you cache a hash in Rails?如何在 Rails 中缓存哈希?
【发布时间】:2016-09-18 07:53:09
【问题描述】:

我正在使用 Rails 4.2.1 和 memcached。我似乎无法缓存哈希。如何缓存哈希?

irb(main):039:0* 
irb(main):040:0* Rails.cache.fetch("development_test") do
irb(main):041:1* 'hi'
irb(main):042:1> end
Cache read: development_test
Cache fetch_hit: development_test
=> "hi"
irb(main):043:0> Rails.cache.fetch("development_test")
Cache read: development_test
=> "hi"
irb(main):044:0> Rails.cache.fetch("development_test") do
irb(main):045:1* {'x' => 3}
irb(main):046:1> end
Cache read: development_test
Cache fetch_hit: development_test
=> "hi"
irb(main):047:0> Rails.cache.fetch("development_test")
Cache read: development_test
=> "hi"
irb(main):048:0> 

【问题讨论】:

  • 您将获得相同的值 ("hi"),因为这是您缓存的值。这是在缓存失效之前您将获得的值(这就是缓存的整个点)。如果要缓存不同的值,则需要使缓存无效或使用不同的键。

标签: ruby-on-rails ruby caching hash memcached


【解决方案1】:

查看文档:http://apidock.com/rails/ActiveSupport/Cache/Store/fetch

使用给定的键从缓存中获取数据。如果缓存中存在具有给定键的数据,则返回该数据。

但是你可以将选项 force 与 true 一起使用:

Rails.cache.fetch("development_test", force: true) do
  {'x' => 3}
end

用于重写缓存值

【讨论】:

  • 这对我不起作用> Rails.cache.fetch("development_test", force: true) { { x: 3 } } NoMethodError: undefined method call' for nil:NilClass 你的意思是?调用者来自 (irb):24:in ''`
【解决方案2】:

我能够将哈希值缓存为 JSON。

def cached_hash
  JSON.parse(
    Rails.cache.fetch("development_test", expires_in: 1.minute) do
      {'x' => 3}.to_json
    end
  )
end

【讨论】:

    猜你喜欢
    • 2017-07-10
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2021-07-25
    • 2014-09-04
    • 2013-12-25
    相关资源
    最近更新 更多