Class: Calculon::Results

Inherits:
Hash
  • Object
show all
Defined in:
lib/calculon/results.rb

Direct Known Subclasses

MultiGroupingResults, SingleGroupingResults

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation) ⇒ Results

Returns a new instance of Results.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/calculon/results.rb', line 7

def initialize(relation)
  super({})

  @bucket_size = relation.calculon_opts[:bybucket]
  @grouped_by = relation.calculon_opts[:group_by] || []
  @grouped_by_values = Set.new

  relation.to_a.each { |row|
    # Keep track of all of the unique column values for the group_by cols
    @grouped_by_values.add @grouped_by.inject({}) { |h, col| h[col] = row.send(col); h }
    self[row.time_bucket] = fetch(row.time_bucket, []) + [row]
  }

  @start_time = relation.calculon_opts[:starttime] || Time.zone.parse(keys.sort.first)
  @start_time = @start_time.to_time if @start_time.is_a?(Date)

  @end_time = relation.calculon_opts[:endtime] || Time.zone.parse(keys.sort.last)
  @end_time = @end_time.to_time if @end_time.is_a?(Date)
end

Instance Attribute Details

#rowsObject (readonly)

Returns the value of attribute rows.



5
6
7
# File 'lib/calculon/results.rb', line 5

def rows
  @rows
end

Class Method Details

.create(relation) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/calculon/results.rb', line 27

def self.create(relation)
  if (relation.calculon_opts[:group_by] || []).length > 0
    MultiGroupingResults.new(relation)
  else
    SingleGroupingResults.new(relation)
  end
end

Instance Method Details

#groupingsObject



35
36
37
# File 'lib/calculon/results.rb', line 35

def groupings
  @grouped_by_values.to_a
end

#map_each_time(&block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/calculon/results.rb', line 49

def map_each_time(&block)
  @time_bucket_names ||= lambda do
    increment_amounts = { :minute => 1.minute, :hour => 1.hour, :day => 1.day, :month => 1.month, :year => 1.year }
    increment = increment_amounts[@bucket_size]

    # get the "floor" of the start and end times (the "floor" bucket)
    current = Time.zone.parse(@start_time.strftime(time_format + " %z"))
    last_time = Time.zone.parse(@end_time.strftime(time_format + " %z"))

    results = []
    while current <= last_time
      results << current.strftime(time_format)
      current += increment
    end
    results
  end.call

  @time_bucket_names.map { |b| block.call(b) }
end

#time_formatObject



39
40
41
42
43
44
45
46
47
# File 'lib/calculon/results.rb', line 39

def time_format
  {
    :minute => "%Y-%m-%d %H:%M:00",
    :hour => "%Y-%m-%d %H:00:00",
    :day => "%Y-%m-%d 00:00:00",
    :month => "%Y-%m-01 00:00:00",
    :year => "%Y-01-01 00:00:00"
  }.fetch(@bucket_size)
end