Class: ForestLiana::PieStatGetter

Inherits:
Object
  • Object
show all
Defined in:
app/services/forest_liana/pie_stat_getter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, params) ⇒ PieStatGetter

Returns a new instance of PieStatGetter.



5
6
7
8
# File 'app/services/forest_liana/pie_stat_getter.rb', line 5

def initialize(resource, params)
  @resource = resource
  @params = params
end

Instance Attribute Details

#recordObject

Returns the value of attribute record.



3
4
5
# File 'app/services/forest_liana/pie_stat_getter.rb', line 3

def record
  @record
end

Instance Method Details

#performObject



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
49
50
51
# File 'app/services/forest_liana/pie_stat_getter.rb', line 10

def perform
  if @params[:group_by_field]
    value = @resource
    conditions = []
    filter_operator = ''

    if @params[:filterType] && @params[:filters]
      filter_operator = " #{@params[:filterType]} ".upcase

      @params[:filters].try(:each) do |filter|
        operator, filter_value = OperatorValueParser.parse(filter[:value])
        conditions <<  OperatorValueParser.get_condition(filter[:field],
          operator, filter_value, @resource)
      end
    end

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

    value = value
      .unscoped
      .where(conditions.join(filter_operator))
      .group(@params[:group_by_field])
      .order("#{@params[:aggregate].downcase}_#{field} DESC")
      .send(@params[:aggregate].downcase, @params[:aggregate_field])
      .map do |k, v|
        # NOTICE: Display the enum name instead of a integer if "enum" type
        if @resource.respond_to?(:defined_enums) &&
           @resource.defined_enums.has_key?(@params[:group_by_field])
          k = @resource.defined_enums[@params[:group_by_field]].invert[k]
        end

        { key: k, value: v }
      end

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