Class: Pokan::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/pokan/query.rb

Overview

The Query class is used to find Entities that obey restrictions. It is commonly used to get a Entity according with a id, get all dead Peers and so on.

Instance Method Summary collapse

Constructor Details

#initialize(entity_class) ⇒ Query

Returns a new instance of Query.



9
10
11
12
# File 'lib/pokan/query.rb', line 9

def initialize(entity_class)
  @entity_class = entity_class
  @db = Connection.redis
end

Instance Method Details

#where(query) ⇒ Object

Returns a array of entities respecting the given restrictions Structure: ‘234’, role: ‘dead’, status:[‘alive’, ‘dead’], random: true…



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pokan/query.rb', line 17

def where(query)
  result = []
  candidates = @db.smembers('entities')

  if query.has_key?(:id)
    query[:id] = [query[:id]]  unless query[:id].is_a?(Array)
    candidates = candidates & query[:id]
  end
  candidates = candidates - query[:not] if query.has_key?(:not)

  candidates.each do |entity_id|
    entity = @entity_class.new
    entity.id = entity_id
    entity.reload
    result << entity  if entity.match?(query.reject {|k, v| k == :not || k == :random || k == :id})
  end

  result = [result.sample] if query[:random]

  result
end