Class: ActiveHashRelation::Aggregation

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/active_hash_relation/aggregation.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#engine_name, #find_model, #model_class_name

Constructor Details

#initialize(resource, params, model: nil) ⇒ Aggregation

Returns a new instance of Aggregation.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/active_hash_relation/aggregation.rb', line 7

def initialize(resource, params, model: nil)
  @configuration = Module.nesting.last.configuration
  @resource = resource
  @params = HashWithIndifferentAccess.new(params)
  @model = model

  unless @model
    @model = model_class_name(@resource)
    if @model.nil? || engine_name == @model.to_s
      @model = model_class_name(@resource, true)
    end
  end
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



5
6
7
# File 'lib/active_hash_relation/aggregation.rb', line 5

def configuration
  @configuration
end

#modelObject (readonly)

Returns the value of attribute model.



5
6
7
# File 'lib/active_hash_relation/aggregation.rb', line 5

def model
  @model
end

#paramsObject (readonly)

Returns the value of attribute params.



5
6
7
# File 'lib/active_hash_relation/aggregation.rb', line 5

def params
  @params
end

#resourceObject (readonly)

Returns the value of attribute resource.



5
6
7
# File 'lib/active_hash_relation/aggregation.rb', line 5

def resource
  @resource
end

Instance Method Details

#applyObject



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
# File 'lib/active_hash_relation/aggregation.rb', line 21

def apply
  if params[:aggregate].is_a? Hash
    meta_attributes = HashWithIndifferentAccess.new

    @model.columns.each do |c|
      next unless params[:aggregate][c.name.to_s].is_a? Hash

      case c.type
      when :integer, :float, :decimal
        meta_attributes[c.name.to_s] = apply_aggregations(
          {avg: :average, sum: :sum, max: :maximum, min: :minimum},
          params[:aggregate][c.name.to_s],
          c.name.to_s
        )
      when :date, :datetime, :timestamp
        meta_attributes[c.name.to_s] = apply_aggregations(
          {max: :maximum, min: :minimum},
          params[:aggregate][c.name.to_s],
          c.name.to_s
        )
      end
    end
  end

  return meta_attributes
end

#apply_aggregations(available_aggr, asked_aggr, column) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/active_hash_relation/aggregation.rb', line 48

def apply_aggregations(available_aggr, asked_aggr, column)
  meta_attributes = HashWithIndifferentAccess.new

  available_aggr.each do |k, v|
    if asked_aggr[k]
      meta_attributes[k] = resource.send(v,column)
      meta_attributes[k] = meta_attributes[k].to_f if meta_attributes[k].is_a? BigDecimal
    end
  end

  return meta_attributes
end