Module: Statisfy::Monthly::ClassMethods

Defined in:
lib/statisfy/monthly.rb

Instance Method Summary collapse

Instance Method Details

#values_grouped_by_month(scope: nil, start_at: nil, stop_at: nil) ⇒ Object

Returns a hash of values grouped by month:

"01/2024" => 33.3,
"02/2024" => 36.6,
"03/2024" => 38.2,

Parameters:

  • scope: (defaults to: nil)

    the scope of the counter (an Organisation or a Department)

  • start_at: (defaults to: nil)

    the date from which you want to start counting (optional)

  • stop_at: (defaults to: nil)

    the date at which you want to stop counting (optional)



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/statisfy/monthly.rb', line 20

def values_grouped_by_month(scope: nil, start_at: nil, stop_at: nil)
  n_months = 24

  if start_at.present? || scope&.created_at.present?
    start_at ||= scope.created_at
    n_months = (Time.zone.today.year * 12 + Time.zone.today.month) - (start_at.year * 12 + start_at.month)
  end

  relevant_months = (0..n_months).map do |i|
    (n_months - i).months.ago.beginning_of_month
  end

  relevant_months
    .filter { |month| stop_at.blank? || month < stop_at }
    .to_h do |month|
    [month.strftime("%m/%Y"), value(scope:, month:).round(2)]
  end
end