class Riak::Crdt::Counter

A distributed counter that supports incrementing and decrementing. This ‘Counter` uses the Riak 2 Data Types feature. If you’re interested in Riak 1.4 Counters, see {Riak::Counter}.

Public Class Methods

new(bucket, key, bucket_type = nil, options = {}) click to toggle source

Create a counter instance. The bucket type is determined by the first of these sources:

  1. The ‘bucket_type` String argument

  2. A {BucketTyped::Bucket} as the ‘bucket` argument

  3. The ‘Crdt::Base::DEFAULT_BUCKET_TYPES` entry

@param [Bucket] bucket the {Riak::Bucket} for this counter @param [String, nil] key The name of the counter. A nil key makes

Riak assign a key.

@param [String] bucket_type The optional bucket type for this counter.

The default is in `Crdt::Base::DEFAULT_BUCKET_TYPES[:counter]`.

@param [Hash] options

Calls superclass method Riak::Crdt::Base::new
# File lib/riak/crdt/counter.rb, line 22
def initialize(bucket, key, bucket_type = nil, options = {})
  super(bucket, key, bucket_type || :counter, options)
end

Public Instance Methods

batch() { |batcher| ... } click to toggle source

Yields a {BatchCounter} to turn multiple increments into a single Riak hit.

@yieldparam [BatchCounter] batch_counter collects multiple increments

# File lib/riak/crdt/counter.rb, line 45
def batch
  batcher = BatchCounter.new

  yield batcher

  increment batcher.accumulator
end
decrement(amount = 1) click to toggle source

Decrement the counter.

@param [Integer] amount

# File lib/riak/crdt/counter.rb, line 58
def decrement(amount = 1)
  increment -amount
end
increment(amount = 1, options = {}) click to toggle source

Increment the counter.

@param [Integer] amount @param [Hash] options

# File lib/riak/crdt/counter.rb, line 37
def increment(amount = 1, options = {})
  operate operation(amount), options
end
pretty_print(pp) click to toggle source
Calls superclass method Riak::Crdt::Base#pretty_print
# File lib/riak/crdt/counter.rb, line 62
def pretty_print(pp)
  super pp do
    pp.comma_breakable
    pp.text "value=#{value}"
  end
end
to_i()
Alias for: value
value() click to toggle source

The current value of the counter; hits the server if the value has not been fetched or if the counter has been incremented.

# File lib/riak/crdt/counter.rb, line 28
def value
  reload if dirty?
  return @value
end
Also aliased as: to_i

Private Instance Methods

operation(amount) click to toggle source
# File lib/riak/crdt/counter.rb, line 74
def operation(amount)
  Operation::Update.new.tap do |op|
    op.type = :counter
    op.value = amount
  end
end
vivify(value) click to toggle source
# File lib/riak/crdt/counter.rb, line 70
def vivify(value)
  @value = value
end