Class: Blodsband::Riak::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/blodsband/riak/counter.rb

Instance Method Summary collapse

Constructor Details

#initialize(bucket, key) ⇒ Counter

Create a concurrent counter.

Parameters:

  • bucket (Blodsband::Riak::Bucket)

    the bucket this counter lives in.

  • key (String)

    the key for this counter.



14
15
16
17
# File 'lib/blodsband/riak/counter.rb', line 14

def initialize(bucket, key)
  @bucket = bucket
  @key = key
end

Instance Method Details

#inc(step = 1) ⇒ Integer

Increment this counter.

Parameters:

  • step (Integer) (defaults to: 1)

    the amount to increment the counter.

Returns:

  • (Integer)

    the new value for this counter. Note that there is no guarantee whatsoever as to at what point this value is true. Only that it was true at some point.

Raises:

  • (RuntimerError)

    if step is < 0



28
29
30
31
32
33
34
# File 'lib/blodsband/riak/counter.rb', line 28

def inc(step = 1)
  raise RuntimeError.new("#{self}.inc(..) only allows positive values") if step < 0
  current = get_resolved
  current["last"] = current["last"] + current["step"]
  current["step"] = step
  val(get_resolved(@bucket.put(@key, current, :riak_params => {:readbody => true})))
end

#val(current = nil) ⇒ Integer

Get the value of this counter.

Parameters:

  • current (Blodsband::Riak::Result) (defaults to: nil)

    a Response defining the last known value (possibly with a gazillion siblings).

Returns:

  • (Integer)

    the current value of the counter. Note that there is no guarantee whatsoever as to when this value was true. Only that it was true at some point.



43
44
45
46
# File 'lib/blodsband/riak/counter.rb', line 43

def val(current = nil)
  current = get_resolved if current.nil?
  return current["last"] + current["step"]
end