Sha256: 3d85e4012b563a79bb1fde0721bca1186f98ca3df72da8987d4f6d576413d684

Contents?: true

Size: 630 Bytes

Versions: 3

Compression:

Stored size: 630 Bytes

Contents

module Counter::Recalculatable
  extend ActiveSupport::Concern

  def recalc!
    if definition.calculated?
      calculate!
    elsif definition.manual?
      raise Counter::Error.new("Can't recalculate a manual counter")
    else
      with_lock do
        new_value = definition.sum? ? sum_by_sql : count_by_sql
        update! value: new_value
      end
    end
  end

  def count_by_sql
    recalc_scope.count
  end

  def sum_by_sql
    recalc_scope.sum(definition.column_to_count)
  end

  # use this scope when recalculating the value
  def recalc_scope
    parent.association(definition.association_name).scope
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
counterwise-0.1.5 app/models/concerns/counter/recalculatable.rb
counterwise-0.1.3 app/models/concerns/counter/recalculatable.rb
counterwise-0.1.2 app/models/concerns/counter/recalculatable.rb