module Sequel::Plugins::LazyAttributes::InstanceMethods

Private Instance Methods

lazy_attribute_lookup(a, opts=OPTS) click to toggle source

If the model was selected with other model objects, eagerly load the attribute for all of those objects. If not, query the database for the attribute for just the current object. Return the value of the attribute for the current object.

    # File lib/sequel/plugins/lazy_attributes.rb
 85 def lazy_attribute_lookup(a, opts=OPTS)
 86   table = opts[:table] || model.table_name
 87   selection = Sequel.qualify(table, a)
 88 
 89   if base_ds = opts[:dataset]
 90     ds = base_ds.where(qualified_pk_hash(table))
 91   else
 92     base_ds = model.dataset
 93     ds = this
 94   end
 95 
 96   if frozen?
 97     return ds.get(selection)
 98   end
 99 
100   if retrieved_with
101     raise(Error, "Invalid primary key column for #{model}: #{pkc.inspect}") unless primary_key = model.primary_key
102     composite_pk = true if primary_key.is_a?(Array)
103     id_map = {}
104     retrieved_with.each{|o| id_map[o.pk] = o unless o.values.has_key?(a) || o.frozen?}
105     predicate_key = composite_pk ? primary_key.map{|k| Sequel.qualify(table, k)} : Sequel.qualify(table, primary_key)
106     base_ds.
107      select(*(Array(primary_key).map{|k| Sequel.qualify(table, k)} + [selection])).
108      where(predicate_key=>id_map.keys).
109      naked.
110      each do |row|
111       obj = id_map[composite_pk ? row.values_at(*primary_key) : row[primary_key]]
112       if obj && !obj.values.has_key?(a)
113         obj.values[a] = row[a]
114       end
115     end
116   end
117   values[a] = ds.get(selection) unless values.has_key?(a)
118   values[a]
119 end