Class: MerryGoRound::Query

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/merry_go_round/query.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

seconds, window

Constructor Details

#initialize(params = {}) ⇒ Query

Returns a new instance of Query.



7
8
9
10
11
12
# File 'lib/merry_go_round/query.rb', line 7

def initialize(params = {})
  self.granularity = params[:granularity] || :hour
  self.keys = [params[:keys]].flatten.compact
  parse_max(params)
  parse_min(params)
end

Instance Attribute Details

#granularityObject

Returns the value of attribute granularity.



5
6
7
# File 'lib/merry_go_round/query.rb', line 5

def granularity
  @granularity
end

#keysObject

Returns the value of attribute keys.



5
6
7
# File 'lib/merry_go_round/query.rb', line 5

def keys
  @keys
end

#maxObject

Returns the value of attribute max.



5
6
7
# File 'lib/merry_go_round/query.rb', line 5

def max
  @max
end

#minObject

Returns the value of attribute min.



5
6
7
# File 'lib/merry_go_round/query.rb', line 5

def min
  @min
end

Instance Method Details

#executeObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/merry_go_round/query.rb', line 14

def execute
  query = MerryGoRound::Aggregation
  if keys && keys.length > 0
    query = query.where('key in (?)', keys)
  end
  query = query.where('granularity = ? and timestamp >= ? and timestamp <= ?', granularity, min, max)
  query = query.order('key, timestamp')

  records = query.all
  keys = records.map(&:key).uniq

  results = keys.inject({}) do |out, current_key|
    out[current_key] = records.select{|record| record.key == current_key }.map do |item|
      {
        id: item.id,
        parent_id: item.parent_id,
        timestamp: item.timestamp,
        value: item.value,
        granularity: item.granularity
      }
    end

    out
  end

  {
    results: results,
    query: self.as_json
  }
end