抽象控制器 Caching
Fragments
片段快取用於快取檢視中的各種區塊,而不快取整個動作。在動作的特定元素經常變更或依賴於複雜狀態,而其他部分不常變更,或可以在多方之間共用時,這很有用。快取會使用動作檢視中提供的 cache
輔助函式來完成。有關詳細資訊,請參閱 ActionView::Helpers::CacheHelper
。
雖然強烈建議您使用根據金鑰的快取過期 (有關詳細資訊,請參閱 CacheHelper 中的連結),但也可以手動使快取過期。例如
expire_fragment('name_of_cache')
執行個體公開方法
combined_fragment_cache_key(金鑰) 連結
給定一個金鑰 (如 expire_fragment
中所述),會傳回一個金鑰陣列,適合用於讀取、寫入或使快取的片段過期。所有金鑰都以 :views
開頭,如果設定,則後面會接 ENV["RAILS_CACHE_ID"]
或 ENV["RAILS_APP_VERSION"]
,接著會接任何控制器範疇的金鑰前綴值,最後是以指定的 金鑰
值結尾。
來源:顯示 | 在 GitHub 上
# 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(金鑰,選項 = nil) 連結
從快取中移除片段。
金鑰
可以採用下列三種形式之一
-
字串
- 這通常會採用路徑形式,例如pages/45/notes
。 -
雜湊
- 視為對url_for
的內隱呼叫,例如{ controller: 'pages', action: 'notes', id: 45}
-
正規表示式
- 會移除任何符合正規表示式的片段,因此%r{pages/\d*/notes}
可能會移除所有筆記。請確定您沒有在正規表示式中使用錨點 (^
或$
),因為實際匹配到的檔案名稱看起來會類似於./cache/filename/path.cache
。注意:正規表示式
過期僅支援在可以遍歷所有金鑰的快取中 (與 memcached 不同)。
選項
會傳遞到快取儲存區的 delete
方法 (或 delete_matched
,適用於 正規表示式
金鑰)。
來源:顯示 | 在 GitHub 上
# 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?(金鑰,選項 = nil) 連結
檢查快取是否來自 金鑰
表示的位置的片段 (有關可接受的格式,請參閱 expire_fragment
)。
來源:顯示 | 在 GitHub 上
# 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(金鑰,選項 = nil) 連結
從 金鑰
表示的位置讀取快取的片段 (有關可接受的格式,請參閱 expire_fragment
)。
原始程式碼:顯示 | 在 GitHub 上檢視
# 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) 連結
將 content
寫入由 key
指出的位置(有關可接受的格式,請參閱 expire_fragment
)。
原始程式碼:顯示 | 在 GitHub 上檢視
# 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