Module: RTM::Sugar::TopicMap::QueryCache

Defined in:
rtm/lib/rtm/sugar/topic_map/query_cache.rb

Instance Method Summary

Instance Method Details

- (Object) cached(*args)

If query caching is enabled, looks up the result of module_name.method_name(parameters) in the cache and if present, returns it. If the result has not yet been stored, executes module_name.method_name(parameters), stores the result and returns it.

If query caching is disabled, executes module_name.method_name(parameters) and returns the result.

:call-seq:

  cached(module_name, method_name, parameters) {method_body} -> result


52
53
54
55
56
57
58
59
60
61
62
63
# File 'rtm/lib/rtm/sugar/topic_map/query_cache.rb', line 52

def cached(*args)
  if @query_cache # Maybe we can optimize this simple if statement away by making enable_query_cache extend the particular TopicMap instance's metaclass. But maybe then the cached version is slower.
    result = @query_cache.fetch(args,:not_found) # :not_found if not cached, if result is nil, we want to cache nil as well.
    if result==:not_found
      result = yield
      @query_cache[args] = result
    end
    return result
  else
    yield #execute without caching
  end
end

- (Object) disable_query_cache

The query cache is disabled by default. Disables the query cache.

:call-seq:

 disable_query_cache -> nil


24
25
26
27
# File 'rtm/lib/rtm/sugar/topic_map/query_cache.rb', line 24

def disable_query_cache
  @query_cache = nil # FIXME: This method is unsafe in multithreaded environments: Setting "@query_cache = nil" while @query_cache is being accessed in method "cached" may cause exceptions to be raised. 
  return
end

- (Object) enable_query_cache

The query cache is disabled by default. Enables the query cache. Does not erase the cache if it was already enabled.

:call-seq:

  enable_query_cache -> nil


14
15
16
17
# File 'rtm/lib/rtm/sugar/topic_map/query_cache.rb', line 14

def enable_query_cache
  @query_cache ||= {}
  return
end

- (Object) reset_query_cache

Erases the query cache. This needs to be invoked every time there is a write access to the topic map.

:call-seq:

  reset_query_cache -> nil


35
36
37
38
# File 'rtm/lib/rtm/sugar/topic_map/query_cache.rb', line 35

def reset_query_cache
  @query_cache = @query_cache? {} : nil
  return
end