Abstract Controller Caching Fragments¶ ↑
片段缓存用于缓存视图中的各种块,而不是缓存整个操作。当操作的某些元素频繁更改或依赖于复杂状态,而其他部分很少更改或可以被多方共享时,这非常有用。缓存是使用 Action View 中可用的 cache 助手完成的。有关更多信息,请参阅 ActionView::Helpers::CacheHelper。
虽然强烈建议您使用基于键的缓存过期(有关更多信息,请参阅 CacheHelper 中的链接),但也可以手动过期缓存。例如:
expire_fragment('name_of_cache')
实例公共方法
combined_fragment_cache_key(key) Link
给定一个键(如 expire_fragment 中所述),返回一个适合读取、写入或过期缓存片段的键数组。所有键都以 :views 开头,后跟 ENV["RAILS_CACHE_ID"] 或 ENV["RAILS_APP_VERSION"](如果已设置),后跟任何控制器范围的键前缀值,最后是指定的 key 值。
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 68 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) Link
从缓存中删除片段。
key 可以采用以下三种形式之一:
-
String- 通常采用路径的形式,例如pages/45/notes。 -
Hash- 被视为对 url_for 的隐式调用,例如{ controller: 'pages', action: 'notes', id: 45} -
Regexp- 将删除任何匹配的片段,因此%r{pages/\d*/notes}可能会删除所有笔记。请确保在正则表达式中不要使用锚点(^或$),因为实际匹配的文件名看起来像./cache/filename/path.cache。注意:只有支持迭代所有键的缓存(不像 memcached)才支持Regexp过期。
options 将被传递给缓存存储的 delete 方法(或 delete_matched,对于 Regexp 键)。
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 131 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) Link
检查位于 key 所指示的位置的缓存片段是否存在(有关可接受的格式,请参阅 expire_fragment)。
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 105 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) Link
从 key 所指示的位置读取缓存片段(有关可接受的格式,请参阅 expire_fragment)。
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 93 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) Link
将 content 写入 key 所指示的位置(有关可接受的格式,请参阅 expire_fragment)。
# File actionpack/lib/abstract_controller/caching/fragments.rb, line 80 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