Class: ForestLiana::LeaderboardStatGetter

Inherits:
StatGetter show all
Defined in:
app/services/forest_liana/leaderboard_stat_getter.rb

Instance Attribute Summary

Attributes inherited from StatGetter

#record

Instance Method Summary collapse

Methods inherited from BaseGetter

#get_collection, #get_resource, #includes_for_serialization

Constructor Details

#initialize(resource, params) ⇒ LeaderboardStatGetter

Returns a new instance of LeaderboardStatGetter.



3
4
5
6
7
8
9
10
11
12
13
# File 'app/services/forest_liana/leaderboard_stat_getter.rb', line 3

def initialize(resource, params)
  @resource = resource
  @params = params
  @model_relationship =  @resource.reflect_on_association(@params[:relationship_field]).klass
  compute_includes()
  @label_field = @params[:label_field]
  @aggregate = @params[:aggregate].downcase
  @aggregate_field = @params[:aggregate_field]
  @limit = @params[:limit]
  @groub_by = "#{@resource.table_name}.#{@label_field}"
end

Instance Method Details

#compute_includesObject



27
28
29
# File 'app/services/forest_liana/leaderboard_stat_getter.rb', line 27

def compute_includes
  @includes = ForestLiana::QueryHelper.get_one_association_names_symbol(@model_relationship)
end

#orderObject



31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/services/forest_liana/leaderboard_stat_getter.rb', line 31

def order
  order = 'DESC'

  # NOTICE: The generated alias for a count is "count_all", for a sum the
  #         alias looks like "sum_#{aggregate_field}"
  if @aggregate == 'sum'
    field = @aggregate_field.downcase
  else
    field = 'all'
  end
  "#{@aggregate}_#{field} #{order}"
end

#performObject



15
16
17
18
19
20
21
22
23
24
25
# File 'app/services/forest_liana/leaderboard_stat_getter.rb', line 15

def perform
  result = @model_relationship
    .joins(@includes)
    .group(@groub_by)
    .order(order)
    .limit(@limit)
    .send(@aggregate, @aggregate_field)
    .map { |key, value| { key: key, value: value } }

  @record = Model::Stat.new(value: result)
end