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 を指定しなかった場合、全てのキャッシュを削除する



500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/helper.rb', line 500

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オブジェクトが生成されるため、 同一性判定のために「どのソース」の「何行目」かで判定を行う



490
491
492
493
# File 'lib/helper.rb', line 490

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

.load(path, options = DEFAULT_OPTIONS) ⇒ Object

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

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



441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/helper.rb', line 441

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



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/helper.rb', line 468

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