Class: Query

Inherits:
Plucky::Query
  • Object
show all
Defined in:
lib/yodel/models/core/mongo/query.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(constructor, site, collection, scope = {}) ⇒ Query

construct a default scope for queries on a resource



5
6
7
8
9
# File 'lib/yodel/models/core/mongo/query.rb', line 5

def initialize(constructor, site, collection, scope={})
  @site = site
  @constructor = constructor
  super(collection, scope)
end

Instance Attribute Details

#constructorObject (readonly)

Returns the value of attribute constructor.



2
3
4
# File 'lib/yodel/models/core/mongo/query.rb', line 2

def constructor
  @constructor
end

#siteObject (readonly)

Returns the value of attribute site.



2
3
4
# File 'lib/yodel/models/core/mongo/query.rb', line 2

def site
  @site
end

Instance Method Details

#distinct(key) ⇒ Object



11
12
13
# File 'lib/yodel/models/core/mongo/query.rb', line 11

def distinct(key)
  record = collection.distinct(key, criteria.to_hash)
end

#find_each(opts = {}) ⇒ Object

TODO: we only cache queries where _id, _site_id, and model are present; _id on its own is a strong enough restriction, so why can’t we cache all queries with id? the query may not match (extra restrictions), but for quries that do match, we should save id-> recrd in cached_records TODO: cache any new records, so they can be matched by single lookups in the future



20
21
22
23
24
25
26
27
28
29
# File 'lib/yodel/models/core/mongo/query.rb', line 20

def find_each(opts={})
  if @site
    super.collect do |values|
      record = @site.cached_records[values['_id']]
      record ? record : @constructor.load(@site, values)
    end
  else
    super.collect {|values| @constructor.load(values)}
  end
end

#find_one(opts = {}) ⇒ Object

override find_one to find objects via an identity hash



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/yodel/models/core/mongo/query.rb', line 35

def find_one(opts={})
  unless @site
    document = super
    return nil if document.nil?
    @constructor.load(document)
  else
    query = clone.amend(opts)
  
    # construct the criteria hash, and remove the keys allowed by a cacheable lookup
    criteria_hash = query.criteria.to_hash
    id = criteria_hash[:_id]
    keys = criteria_hash.keys
    keys -= [:_id, :_site_id, :model]
  
    # queries are cacheable if they are looking for a single ID
    cacheable = !id.nil? && id.is_a?(BSON::ObjectId) && keys.empty?
  
    # lookup the record in the cache
    if cacheable
      record = @site.cached_records[id]
      return record unless record.nil?
    end
  
    # lookup failed, so perform a query
    record = query.collection.find_one(criteria_hash, query.options.to_hash)
    if record
      record = @constructor.load(@site, record)
      @site.cached_records[id] = record if cacheable
    end
  
    record
  end
end