This repository has been archived on 2024-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
ace-of-base/lib/ace_of_base/aggregated_record.rb

59 lines
1.2 KiB
Ruby
Raw Normal View History

2019-07-15 19:03:58 +12:00
# frozen_string_literal: true
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