57 lines
1.2 KiB
Ruby
57 lines
1.2 KiB
Ruby
|
module AceOfBase
|
||
|
# Aggregates records together.
|
||
|
class AggregatedRecord
|
||
|
def initialize(records, aggregations)
|
||
|
@records = records
|
||
|
@aggregations = aggregations
|
||
|
end
|
||
|
|
||
|
AceOfBase::Record::ATTRIBUTES.each do |field|
|
||
|
define_method field do
|
||
|
aggregate_field(field)
|
||
|
end
|
||
|
end
|
||
|
|
||
|
private
|
||
|
|
||
|
attr_reader :records, :aggregations
|
||
|
|
||
|
def aggregate_field(field)
|
||
|
return records.first.public_send(field) unless aggregations.keys.include?(field)
|
||
|
|
||
|
send("aggregate_field_with_#{aggregations[field]}", field)
|
||
|
end
|
||
|
|
||
|
def aggregate_field_with_min(field)
|
||
|
records
|
||
|
.map { |record| record.public_send(field) }
|
||
|
.min
|
||
|
end
|
||
|
|
||
|
def aggregate_field_with_max(field)
|
||
|
records
|
||
|
.map { |record| record.public_send(field) }
|
||
|
.min
|
||
|
end
|
||
|
|
||
|
def aggregate_field_with_sum(field)
|
||
|
records
|
||
|
.map { |record| record.public_send(field) }
|
||
|
.reduce(:+)
|
||
|
end
|
||
|
|
||
|
def aggregate_field_with_count(field)
|
||
|
records
|
||
|
.map { |record| record.public_send(field) }
|
||
|
.uniq
|
||
|
.size
|
||
|
end
|
||
|
|
||
|
def aggregate_field_with_collect(field)
|
||
|
records
|
||
|
.map { |record| record.public_send(field) }
|
||
|
.uniq
|
||
|
end
|
||
|
end
|
||
|
end
|