Module: TaliaCore::ActiveSourceParts::PredicateHandler::ClassMethods

Included in:
TaliaCore::ActiveSource
Defined in:
lib/talia_core/active_source_parts/predicate_handler.rb

Overview

Predicate-related class methods. See the PredicateHandler module for more

Instance Method Summary collapse

Instance Method Details

#prefetch_relations_for(sources, limit = 1024) ⇒ Object

Attempts to fetch all relations on the given sources at once, so that there is potentially only one.

For safety reasons, there is a limit on the number of sources that is accepted. (For a web application, if you go over the default, you’re probably doing it wrong).

When prefetching, all the relations/properties for the given sources are loaded in a single request, and the data is injected in the internal cache of the sources.

A source with prefetched relations will not cause database queries if you access its properties.

Raises:

  • (RangeError)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/talia_core/active_source_parts/predicate_handler.rb', line 33

def prefetch_relations_for(sources, limit = 1024)
  sources = [ sources ] if(sources.is_a?(ActiveSource))
  raise(RangeError, "Too many sources for prefetching.") if(sources.size > limit)
  src_hash = {}
  sources.each { |src| src_hash[src.id] = src }
  
  relations = SemanticRelation.find(:all, :conditions => { :subject_id => src_hash.keys }, :include => [:subject, :object])
  
  relations.each do |rel|
    src_hash[rel.subject_id].inject_predicate(rel)
  end

  # Set all as loaded
  sources.each do |src|
    src.each_cached_wrapper { |wrap| wrap.instance_variable_set(:'@loaded', true) }
    src.instance_variable_set(:'@prefetched', true)
  end
end