Class: Mementus::Relation::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/mementus/relation.rb

Overview

Chainable query object that delegates to the given relation.

Instance Method Summary collapse

Constructor Details

#initialize(relation, cache) ⇒ Query

Returns a new instance of Query.



22
23
24
25
# File 'lib/mementus/relation.rb', line 22

def initialize(relation, cache)
  @relation = relation
  @cache = cache
end

Instance Method Details

#countObject

Number of objects.



62
63
64
# File 'lib/mementus/relation.rb', line 62

def count
  objects.count
end

#each(&block) ⇒ Object

Enumerate over each object.



55
56
57
58
59
# File 'lib/mementus/relation.rb', line 55

def each(&block)
  @relation.each do |relation|
    yield block
  end
end

#objectsObject

Materializes the relation to an array of model objects.



48
49
50
51
52
# File 'lib/mementus/relation.rb', line 48

def objects
  @relation.inject([]) do |list, relation|
    list << @cache[relation[:__cache_key]]
  end
end

#order(constraints) ⇒ Object

Order the collection by attribute and direction



36
37
38
39
40
41
42
43
44
45
# File 'lib/mementus/relation.rb', line 36

def order(constraints)
  ordered_relation = @relation.sort_by do |relation|
    constraints.keys.inject([]) do |list, constraint|
      direction = constraints[constraint].to_sym
      direction = :asc unless direction == :desc
      list << relation.send(constraint.to_sym).send(direction)
    end
  end
  Query.new(ordered_relation, @cache)
end

#where(constraints) ⇒ Object

Filters the collection based on the given constraints.

  • Pass in a key-value hash to filter based on matching attributes by equality.

  • Pass in a block to construct a more specialised predicate match.



31
32
33
# File 'lib/mementus/relation.rb', line 31

def where(constraints)
  Query.new(@relation.restrict(constraints), @cache)
end