抽象控制器 Caching
Fragments
片段缓存用于缓存视图中的各种块,而无需缓存整个操作。当操作的某些元素频繁更改或依赖于复杂状态,而其他部分很少更改或可以在多个方之间共享时,这非常有用。缓存使用 Action View 中提供的 cache
帮助器完成。有关详细信息,请参阅 ActionView::Helpers::CacheHelper
。
虽然强烈建议您使用基于密钥的缓存过期(有关详细信息,请参阅 CacheHelper 中的链接),但也可以手动使缓存过期。例如
expire_fragment('name_of_cache')
实例公共方法
combined_fragment_cache_key(key) 链接
给定一个密钥(如 expire_fragment
中所述),返回一个密钥数组,适用于读取、写入或使缓存片段过期。所有密钥都以 :views
开头,如果已设置,则后跟 ENV["RAILS_CACHE_ID"]
或 ENV["RAILS_APP_VERSION"]
,后跟任何控制器范围的密钥前缀值,最后以指定的 key
值结尾。
来源:显示 | 在 GitHub 上
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 70 def combined_fragment_cache_key(key) head = self.class.fragment_cache_keys.map { |k| instance_exec(&k) } tail = key.is_a?(Hash) ? url_for(key).split("://").last : key cache_key = [:views, ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"], head, tail] cache_key.flatten!(1) cache_key.compact! cache_key end
expire_fragment(key, options = nil) 链接
从缓存中删除片段。
key
可以采用以下三种形式之一
-
String
- 这通常采用路径的形式,如pages/45/notes
。 -
Hash
- 视为对url_for
的隐式调用,如{ controller: 'pages', action: 'notes', id: 45}
-
Regexp
- 将删除任何匹配的片段,因此%r{pages/\d*/notes}
可能会删除所有注释。确保不要在正则表达式中使用锚点(^
或$
),因为匹配的实际文件名看起来像./cache/filename/path.cache
。注意:Regexp
过期仅支持可以迭代所有密钥的缓存(与 memcached 不同)。
options
传递给缓存存储的 delete
方法(或 delete_matched
,适用于 Regexp
键)。
来源:显示 | 在 GitHub 上
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 134 def expire_fragment(key, options = nil) return unless cache_configured? key = combined_fragment_cache_key(key) unless key.is_a?(Regexp) instrument_fragment_cache :expire_fragment, key do if key.is_a?(Regexp) cache_store.delete_matched(key, options) else cache_store.delete(key, options) end end end
fragment_exist?(key, options = nil) 链接
检查由 key
表示的位置的缓存片段是否存在(有关可接受格式,请参见 expire_fragment
)。
来源:显示 | 在 GitHub 上
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 107 def fragment_exist?(key, options = nil) return unless cache_configured? key = combined_fragment_cache_key(key) instrument_fragment_cache :exist_fragment?, key do cache_store.exist?(key, options) end end
read_fragment(key, options = nil) 链接
从由 key
表示的位置读取缓存片段(有关可接受格式,请参见 expire_fragment
)。
来源:显示 | 在 GitHub 上
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 95 def read_fragment(key, options = nil) return unless cache_configured? key = combined_fragment_cache_key(key) instrument_fragment_cache :read_fragment, key do result = cache_store.read(key, options) result.respond_to?(:html_safe) ? result.html_safe : result end end
write_fragment(key, content, options = nil) 链接
将 content
写入由 key
表示的位置(有关可接受格式,请参见 expire_fragment
)。
来源:显示 | 在 GitHub 上
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 82 def write_fragment(key, content, options = nil) return content unless cache_configured? key = combined_fragment_cache_key(key) instrument_fragment_cache :write_fragment, key do content = content.to_str cache_store.write(key, content, options) end content end