Class: Riml::IncludeCache

Inherits:
Object
  • Object
show all
Defined in:
lib/riml/include_cache.rb

Instance Method Summary collapse

Constructor Details

#initializeIncludeCache

Returns a new instance of IncludeCache.



4
5
6
7
8
9
# 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

Instance Method Details

#[](included_filename) ⇒ Object

Not used internally but might be useful as an API



36
37
38
# File 'lib/riml/include_cache.rb', line 36

def [](included_filename)
  @m.synchronize { @cache[included_filename] }
end

#clearObject

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



42
43
44
45
# File 'lib/riml/include_cache.rb', line 42

def clear
  @m.synchronize { @cache.clear }
  self
end

#fetch(included_filename) ⇒ Object

‘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.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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