module Sequel::Plugins::LazyAttributes::InstanceMethods

def lazy_attribute_lookup(a, opts=OPTS)

the attribute for the current object.
the attribute for just the current object. Return the value of
attribute for all of those objects. If not, query the database for
If the model was selected with other model objects, eagerly load the
def lazy_attribute_lookup(a, opts=OPTS)
  table = opts[:table] || model.table_name
  selection = Sequel.qualify(table, a)
  if base_ds = opts[:dataset]
    ds = base_ds.where(qualified_pk_hash(table))
  else
    base_ds = model.dataset
    ds = this
  end
  if frozen?
    return ds.get(selection)
  end
  if retrieved_with
    primary_key = model.primary_key
    composite_pk = true if primary_key.is_a?(Array)
    id_map = {}
    retrieved_with.each{|o| id_map[o.pk] = o unless o.values.has_key?(a) || o.frozen?}
    predicate_key = composite_pk ? primary_key.map{|k| Sequel.qualify(table, k)} : Sequel.qualify(table, primary_key)
    base_ds.
     select(*(Array(primary_key).map{|k| Sequel.qualify(table, k)} + [selection])).
     where(predicate_key=>id_map.keys).
     naked.
     each do |row|
      obj = id_map[composite_pk ? row.values_at(*primary_key) : row[primary_key]]
      if obj && !obj.values.has_key?(a)
        obj.values[a] = row[a]
      end
    end
  end
  values[a] = ds.get(selection) unless values.has_key?(a)
  values[a]
end