class Riml::IncludeCache

Public Class Methods

new() click to toggle source
# File lib/riml/include_cache.rb, line 4
def initialize
  @cache = {}
  @m = Mutex.new
  # Only Ruby 2.0+ has Mutex#owned? method
  @owns_lock = nil
end

Public Instance Methods

[](included_filename) click to toggle source

Not used internally but might be useful as an API

# File lib/riml/include_cache.rb, line 36
def [](included_filename)
  @m.synchronize { @cache[included_filename] }
end
clear() click to toggle source

‘clear` should only be called by the main thread that is using the `Riml.compile_files` method.

# File lib/riml/include_cache.rb, line 42
def clear
  @m.synchronize { @cache.clear }
  self
end
fetch(included_filename) { || ... } click to toggle source

‘fetch` can be called recursively in the `yield`ed block, so must make sure not to try to lock the Mutex if it’s already locked by the current thread, as this would result in an error.

# File lib/riml/include_cache.rb, line 14
def fetch(included_filename)
  if source = @cache[included_filename]
    return source
  end

  if @m.locked? && @owns_lock == Thread.current
    @cache[included_filename] = yield
  else
    ret = nil
    @cache[included_filename] = @m.synchronize do
      begin
        @owns_lock = Thread.current
        ret = yield
      ensure
        @owns_lock = nil
      end
    end
    ret
  end
end