Module: CalculateAll

Defined in:
lib/calculate-all.rb,
lib/calculate-all/version.rb

Defined Under Namespace

Modules: Helpers, Querying

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Instance Method Details

#calculate_all(*function_aliases, **functions, &block) ⇒ Object


5
6
7
8
9
10
11
12
13
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
44
45
46
47
48
# File 'lib/calculate-all.rb', line 5

def calculate_all(*function_aliases, **functions, &block)
  if function_aliases.size == 1 && functions == {}
    return_plain_values = true
  end
  functions.merge!(
    CalculateAll::Helpers.decode_function_aliases(function_aliases)
  )
  if functions == {}
    raise ArgumentError, "provide at least one function to calculate"
  end
  # groupdate compatibility
  group_values = self.group_values
  if !group_values.is_a?(Array) && group_values.respond_to?(:relation)
    group_values = group_values.relation
  end
  if functions.size == 1 && group_values.size == 0
    plain_rows = true
  end

  results = {}

  pluck(*group_values, *functions.values).each do |row|
    row = [row] if plain_rows
    if return_plain_values
      value = row.last
    else
      value = functions.keys.zip(row.last(functions.size)).to_h
    end

    value = block.call(value) if block

    # Return unwrapped hash directly for scope without any .group()
    return value if group_values.empty?

    if group_values.size == 1
      key = row.first
    else
      key = row.first(group_values.size)
    end
    results[key] = value
  end

  results
end