Class: Redstruct::Types::Counter

Inherits:
String show all
Includes:
Utils::Scriptable
Defined in:
lib/redstruct/types/counter.rb

Instance Attribute Summary

Attributes inherited from Base

#key

Instance Method Summary collapse

Methods included from Utils::Scriptable

included

Methods inherited from String

#delete_if_equals, #delete_if_equals_script, #length, #slice

Methods included from Utils::Coercion

coerce_array, coerce_bool

Methods inherited from Struct

#delete, #exists?, #expire, #expire_at, #persist, #type

Methods included from Utils::Inspectable

#inspect, #to_s

Methods inherited from Base

#to_h, #with

Constructor Details

#initialize(increment: 1, max: nil, **options) ⇒ Counter

Returns a new instance of Counter.



6
7
8
9
10
# File 'lib/redstruct/types/counter.rb', line 6

def initialize(increment: 1, max: nil, **options)
  super(**options)
  @increment = increment
  @max = max
end

Instance Method Details

#decrement(by: nil, max: nil) ⇒ Object



33
34
35
36
37
# File 'lib/redstruct/types/counter.rb', line 33

def decrement(by: nil, max: nil)
  by ||= @increment
  by = -by.to_i
  return increment(by: by, max: max)
end

#getObject



12
13
14
# File 'lib/redstruct/types/counter.rb', line 12

def get
  super.to_i
end

#getset(value) ⇒ Object



39
40
41
# File 'lib/redstruct/types/counter.rb', line 39

def getset(value)
  return super(value.to_i).to_i
end

#increment(by: nil, max: nil) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/redstruct/types/counter.rb', line 20

def increment(by: nil, max: nil)
  by ||= @increment
  max ||= @max

  value = if max.nil?
    self.connection.incrby(@key, by.to_i).to_i
  else
    ring_increment_script(keys: @key, argv: [by.to_i, max.to_i]).to_i
  end

  return value
end

#inspectable_attributesObject

Helper method for easy inspection



60
61
62
# File 'lib/redstruct/types/counter.rb', line 60

def inspectable_attributes
  super.merge(max: @max, increment: @increment)
end

#set(value) ⇒ Object



16
17
18
# File 'lib/redstruct/types/counter.rb', line 16

def set(value)
  super(value.to_i)
end