Class: Riak::Crdt::Counter

Inherits:
Base show all
Defined in:
lib/riak/crdt/counter.rb

Overview

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.

Instance Attribute Summary

Attributes inherited from Base

#bucket, #bucket_type, #key

Instance Method Summary collapse

Methods inherited from Base

#==, #context?, #dirty?, #inspect_name, #pretty_print_cycle, #reload

Methods included from Util::Translation

#i18n_scope, #t

Constructor Details

#initialize(bucket, key, bucket_type = nil, options = {}) ⇒ Counter

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

Parameters:

  • bucket (Bucket)

    the Bucket for this counter

  • key (String, nil)

    The name of the counter. A nil key makes Riak assign a key.

  • bucket_type (String) (defaults to: nil)

    The optional bucket type for this counter. The default is in ‘Crdt::Base::DEFAULT_BUCKET_TYPES`.

  • options (Hash) (defaults to: {})


22
23
24
# File 'lib/riak/crdt/counter.rb', line 22

def initialize(bucket, key, bucket_type = nil, options = {})
  super(bucket, key, bucket_type || :counter, options)
end

Instance Method Details

#batch {|batch_counter| ... } ⇒ Object

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

Yield Parameters:

  • batch_counter (BatchCounter)

    collects multiple increments



45
46
47
48
49
50
51
# File 'lib/riak/crdt/counter.rb', line 45

def batch
  batcher = BatchCounter.new

  yield batcher

  increment batcher.accumulator
end

#decrement(amount = 1) ⇒ Object

Decrement the counter.

Parameters:

  • amount (Integer) (defaults to: 1)


58
59
60
# File 'lib/riak/crdt/counter.rb', line 58

def decrement(amount = 1)
  increment -amount
end

#increment(amount = 1, options = {}) ⇒ Object

Increment the counter.

Parameters:

  • amount (Integer) (defaults to: 1)
  • options (Hash) (defaults to: {})


37
38
39
# File 'lib/riak/crdt/counter.rb', line 37

def increment(amount = 1, options = {})
  operate operation(amount), options
end

#pretty_print(pp) ⇒ Object



62
63
64
65
66
67
# File 'lib/riak/crdt/counter.rb', line 62

def pretty_print(pp)
  super pp do
    pp.comma_breakable
    pp.text "value=#{value}"
  end
end

#valueObject Also known as: to_i

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



28
29
30
31
# File 'lib/riak/crdt/counter.rb', line 28

def value
  reload if dirty?
  return @value
end