Sha256: 6daeef67dcb9a40d9790c91dce27250dc5b3a50efbcb1f7d3a7b26de01970598

Contents?: true

Size: 921 Bytes

Versions: 6

Compression:

Stored size: 921 Bytes

Contents

module Counter::Increment
  extend ActiveSupport::Concern

  included do
    def increment! by: 1
      perform_update! by
    end

    def decrement! by: 1
      perform_update!(-by)
    end

    def perform_update! increment
      return if increment.zero?

      with_lock do
        update! value: value + increment
      end
    end

    def add_item item
      return unless increment?(item, :create)

      increment! by: increment_from_item(item)
    end

    def remove_item item
      return unless decrement?(item, :delete)

      decrement! by: increment_from_item(item)
    end

    def update_item item
      if increment?(item, :update)
        increment! by: increment_from_item(item)
      end

      if decrement?(item, :update)
        decrement! by: increment_from_item(item)
      end
    end

    # How much should we increment the counter
    def increment_from_item item
      1
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
counterwise-0.1.5 app/models/concerns/counter/increment.rb
counterwise-0.1.4 app/models/concerns/counter/increment.rb
counterwise-0.1.3 app/models/concerns/counter/increment.rb
counterwise-0.1.2 app/models/concerns/counter/increment.rb
counterwise-0.1.1 app/models/concerns/counter/increment.rb
counterwise-0.1.0 app/models/concerns/counter/increment.rb