Module: Rql::Dsl::Aggregations

Included in:
Context
Defined in:
lib/rql/dsl/aggregations.rb

Instance Method Summary collapse

Instance Method Details

#average(attribute) ⇒ Object



16
17
18
# File 'lib/rql/dsl/aggregations.rb', line 16

def average(attribute)
  calculate(attribute, :average)
end

#calculate(attribute, operation) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/rql/dsl/aggregations.rb', line 4

def calculate(attribute, operation)
  association = @name.to_s.classify.constantize
  sum_table_name = "#{@model.name.underscore}_#{attribute}_#{operation.to_s.pluralize}"
  subquery = @scope.joins(@name).group(:id).select(:id, association.arel_table[attribute].send(operation)).arel.as(sum_table_name)
  query = Arel.sql("COALESCE((#{@model.from(subquery).where(@model.arel_table[:id].eq(subquery[:id])).select(subquery[operation]).to_sql}), 0)")
  Context.new(@model, query)
end

#count(attribute = :id) ⇒ Object



28
29
30
# File 'lib/rql/dsl/aggregations.rb', line 28

def count(attribute = :id)
  calculate(attribute, :count)
end

#maximum(attribute) ⇒ Object



24
25
26
# File 'lib/rql/dsl/aggregations.rb', line 24

def maximum(attribute)
  calculate(attribute, :maximum)
end

#minimum(attribute) ⇒ Object



20
21
22
# File 'lib/rql/dsl/aggregations.rb', line 20

def minimum(attribute)
  calculate(attribute, :minimum)
end

#sum(attribute) ⇒ Object



12
13
14
# File 'lib/rql/dsl/aggregations.rb', line 12

def sum(attribute)
  calculate(attribute, :sum)
end