跳至內容 跳至搜尋

檔案更新檢查器

FileUpdateChecker 規格化 Rails 用於監視檔案以及控制重新載入的 API。API 取決於下方所述的四個方法。

  • initialization 預期兩個參數和一個區塊,如下所述。

  • updated? 如果檔案系統有更新,則傳回布林值,否則傳回 false。

  • execute 在初始化時執行提供的區塊並更新最新監視的檔案與時間戳記。

  • execute_if_updated 僅在更新時執行區塊。

初始化後,呼叫 execute_if_updated 僅會在檔案系統確實有變更時執行區塊。

此類別由 Rails 使用,在每個新要求時重新載入 I18n 框架。

i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
  I18n.reload!
end

ActiveSupport::Reloader.to_prepare do
  i18n_reloader.execute_if_updated
end
方法
E
N
U

類別公開方法

new(files, dirs = {}, &block)

它在初始化時接受兩個參數,第一個參數為檔案陣列,第二個參數為目錄雜湊(選用)。雜湊的 key 必須為目錄,而 value 必須為要於該目錄下監視的附檔名陣列。

此方法還必須接收一個區塊,當路徑變更時該區塊將被呼叫。在 FileUpdateChecker 初始化之後,無法變更檔案陣列和目錄清單。

# File activesupport/lib/active_support/file_update_checker.rb, line 44
def initialize(files, dirs = {}, &block)
  unless block
    raise ArgumentError, "A block is required to initialize a FileUpdateChecker"
  end

  @files = files.freeze
  @glob  = compile_glob(dirs)
  @block = block

  @watched    = nil
  @updated_at = nil

  @last_watched   = watched
  @last_update_at = updated_at(@last_watched)
end

實例公開方法

execute()

執行提供的區塊並更新最新監視的檔案與時間戳記。

# File activesupport/lib/active_support/file_update_checker.rb, line 82
def execute
  @last_watched   = watched
  @last_update_at = updated_at(@last_watched)
  @block.call
ensure
  @watched = nil
  @updated_at = nil
end

execute_if_updated()

如果已更新,則執行提供的區塊。

# File activesupport/lib/active_support/file_update_checker.rb, line 92
def execute_if_updated
  if updated?
    yield if block_given?
    execute
    true
  else
    false
  end
end

updated?()

檢查是否有任何條目已更新。如果有的話,則會快取監視和/或 updated_at 的值,直到透過 executeexecute_if_updated 執行區塊為止。

# File activesupport/lib/active_support/file_update_checker.rb, line 63
def updated?
  current_watched = watched
  if @last_watched.size != current_watched.size
    @watched = current_watched
    true
  else
    current_updated_at = updated_at(current_watched)
    if @last_update_at < current_updated_at
      @watched    = current_watched
      @updated_at = current_updated_at
      true
    else
      false
    end
  end
end