Module: Helper::CacheLoader

Defined in:
lib/helper.rb

Overview

更新時刻を考慮したファイルのローダー

Constant Summary collapse

DEFAULT_OPTIONS =
{ mode: "r:BOM|UTF-8" }
@@mutex =
Mutex.new
@@caches =
{}
@@result_caches =
{}

Class Method Summary collapse

Class Method Details

.clear(path = nil) ⇒ Object

指定したファイルのキャッシュを削除する

path を指定しなかった場合、全てのキャッシュを削除する



404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/helper.rb', line 404

def clear(path = nil)
  @@mutex.synchronize do
    if path
      fullpath = File.expand_path(path)
      @@cache.delete(fullpath)
      @@result_caches.delete(fullpath)
    else
      @@cache.clear
      @@result_caches.clear
    end
  end
end

.generate_key(fullpath, block) ⇒ Object

キャッシュを格納する際に必要なキーを生成する

ブロックはその場所が実行されるたびに違うprocオブジェクトが生成されるため、 同一性判定のために「どのソース」の「何行目」かで判定を行う



394
395
396
397
# File 'lib/helper.rb', line 394

def generate_key(fullpath, block)
  src, line = block.source_location
  "#{fullpath}:#{src}:#{line}"
end

.load(path, options = DEFAULT_OPTIONS) ⇒ Object

ファイルの更新時刻を考慮してファイルのデータを取得する。 前回取得した時からファイルが変更されていない場合は、キャッシュを返す

options にはファイルを読み込む時に File.read に渡すオプションを指定できる



345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/helper.rb', line 345

def load(path, options = DEFAULT_OPTIONS)
  @@mutex.synchronize do
    fullpath = File.expand_path(path)
    cache_data = @@caches[fullpath]
    if Helper.file_latest?(fullpath) || !cache_data
      body = File.read(fullpath, options)
      @@caches[fullpath] = body
      return body
    else
      return cache_data
    end
  end
end

.memo(path, options = DEFAULT_OPTIONS, &block) ⇒ Object

ファイルを処理するブロックの結果をキャッシュ化する

CacheLoader.load がファイルの中身だけをキャッシュ化するのに対して これはブロックの結果をキャッシュする。ファイルが更新されない限り、 ブロックの結果は変わらない

ex.) Helper::CacheLoader.memo(“filepath”) do |data|

# data に関する処理
result  # ここで nil を返すと次回も再度読み込まれる

end



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/helper.rb', line 372

def memo(path, options = DEFAULT_OPTIONS, &block)
  @@mutex.synchronize do
    fail ArgumentError, "need a block" unless block
    fullpath = File.expand_path(path)
    key = generate_key(fullpath, block)
    cache = @@result_caches[key]
    if Helper.file_latest?(fullpath) || !cache
      data = File.read(fullpath, options)
      @@result_caches[key] = result = block.call(data)
      return result
    else
      return cache
    end
  end
end