【问题标题】:Is there a way to cache a string fragment within a helper method?有没有办法在辅助方法中缓存字符串片段?
【发布时间】:2013-07-09 08:15:09
【问题描述】:

我有一个助手可以为引擎中的常见组件生成复杂的 HTML。

助手(非常简单):

def component(name)
  component = Component.find_by_name!(name)
  # a whole lot of complex stuff that uses component to build some HTML
end

查看:

<%= component(:my_component) %>

我想在这些组件上实现片段缓存,但我想在 #component 本身内执行它以保持事物干燥,例如

def component(name)
  ...

  cache some_unique_fragment_name do
    html
  end

  # or, more succinctly:
  cache(some_unique_fragment_name, html)
end

问题是 Rails 的 cache 助手希望它会在 Erb 中包装一个 HTML 块,因此不会像我上面描述的那样工作。

有没有办法将#cache 用于辅助方法中的字符串片段?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    我是fetch 块的忠实粉丝,您可以在Rails docs 阅读更多内容:

    def component(name)
      # ...
    
      cache.fetch('some_unique_fragment_name') do
        html
      end
    end
    

    如果它可用,它将返回some_unique_fragment_name 的值,否则它将在块内生成它。这是一种显示缓存正在发生的可读、清晰的方式。

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多