Class: Prato::Types::AggregateColumn

Inherits:
Object
  • Object
show all
Defined in:
lib/prato/types/aggregate_column.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aggregate_function, aggregate_accessor, format: nil, filter: nil) ⇒ AggregateColumn

Returns a new instance of AggregateColumn.



8
9
10
11
12
13
# File 'lib/prato/types/aggregate_column.rb', line 8

def initialize(aggregate_function, aggregate_accessor, format: nil, filter: nil)
  @accessor = Array(aggregate_accessor)
  @aggregate_function = aggregate_function
  @format = format
  @filter = filter
end

Instance Attribute Details

#arel_nodeObject (readonly)

Returns the value of attribute arel_node.



6
7
8
# File 'lib/prato/types/aggregate_column.rb', line 6

def arel_node
  @arel_node
end

#filterObject (readonly)

Returns the value of attribute filter.



6
7
8
# File 'lib/prato/types/aggregate_column.rb', line 6

def filter
  @filter
end

#formatObject (readonly)

Returns the value of attribute format.



6
7
8
# File 'lib/prato/types/aggregate_column.rb', line 6

def format
  @format
end

Instance Method Details

#extract_value(record, _) ⇒ Object



53
54
55
# File 'lib/prato/types/aggregate_column.rb', line 53

def extract_value(record, _)
  record[@sql_alias]
end

#resolve_arel!(base_model, display_id) ⇒ Object



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
# File 'lib/prato/types/aggregate_column.rb', line 15

def resolve_arel!(base_model, display_id)
  association_path = @aggregate_function == :count ? @accessor : @accessor[0..-2]
  aggregate_field = @aggregate_function == :count ? nil : @accessor[-1]

  reflections = resolve_reflections(base_model, association_path)
  base_table = base_model.arel_table
  aliased_tables = reflections.each_with_index.map do |reflection, index|
    Arel::Table.new(reflection.klass.table_name, as: "prato_agg_#{index}_#{reflection.klass.table_name}")
  end
  target_table = aliased_tables.last

  subquery = target_table.project(aggregate_expression(target_table, @aggregate_function, aggregate_field))

  (reflections.length - 1).downto(1) do |i|
    ref = reflections[i]
    source_table = aliased_tables[i - 1]
    subquery = subquery.join(source_table).on(
      association_condition(ref, source_table, aliased_tables[i])
    )
  end

  first_ref = reflections.first
  subquery = subquery.where(
    association_condition(first_ref, base_table, aliased_tables.first)
  )

  @arel_node = Arel::Nodes::Grouping.new(subquery)
  @sql_alias = display_id.to_s
end

#select_nodeObject



49
50
51
# File 'lib/prato/types/aggregate_column.rb', line 49

def select_node
  Arel::Nodes::As.new(@arel_node, Arel.sql(@sql_alias))
end

#sql_node_for(_scope) ⇒ Object



45
46
47
# File 'lib/prato/types/aggregate_column.rb', line 45

def sql_node_for(_scope)
  @arel_node
end