Class: Qtrix::Queue

Inherits:
Object
  • Object
show all
Includes:
Namespacing
Defined in:
lib/qtrix/queue.rb

Constant Summary collapse

REDIS_KEY =
:queue_weights

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Namespacing

#extract_args, included, #redis, #redis_namespace

Constructor Details

#initialize(ns, name, weight) ⇒ Queue

Returns a new instance of Queue.



55
56
57
58
59
# File 'lib/qtrix/queue.rb', line 55

def initialize(ns, name, weight)
  @namespace = ns
  @name = name.to_sym
  @weight = weight.to_f
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



53
54
55
# File 'lib/qtrix/queue.rb', line 53

def name
  @name
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



53
54
55
# File 'lib/qtrix/queue.rb', line 53

def namespace
  @namespace
end

Class Method Details

.all_queues(namespace = :current) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/qtrix/queue.rb', line 19

def all_queues(namespace=:current)
  raw = redis(namespace).zrevrange(REDIS_KEY, 0, -1, withscores: true)
  [].tap {|result|
    raw.each_slice(2) do |tuple|
      result << self.new(namespace, tuple[0], tuple[1].to_f)
    end
  }
end

.clear!(namespace = :current) ⇒ Object



36
37
38
39
# File 'lib/qtrix/queue.rb', line 36

def clear!(namespace=:current)
  redis(namespace).del REDIS_KEY
  Qtrix::Matrix.clear! namespace
end

.count(namespace = :current) ⇒ Object



28
29
30
# File 'lib/qtrix/queue.rb', line 28

def count(namespace=:current)
  redis(namespace).zcard(REDIS_KEY)
end

.map_queue_weights(*args) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/qtrix/queue.rb', line 10

def map_queue_weights(*args)
  namespace, map = extract_args(1, *args)
  map.each {|queue, weight| validate(queue.to_s, weight.to_f)}
  self.clear!(namespace)
  map.each {|queue, weight| redis(namespace).zadd(REDIS_KEY, weight.to_f, queue.to_s)}
  Qtrix::Matrix.clear!(namespace)
end

.total_weight(ns = :current) ⇒ Object



32
33
34
# File 'lib/qtrix/queue.rb', line 32

def total_weight(ns=:current)
  all_queues(ns).inject(0) {|memo, queue| memo += queue.weight}
end

Instance Method Details

#==(other) ⇒ Object



61
62
63
# File 'lib/qtrix/queue.rb', line 61

def ==(other)
  name == other.name && weight == other.weight
end

#hashObject



65
66
67
# File 'lib/qtrix/queue.rb', line 65

def hash
  name.hash - weight.hash
end

#resource_percentageObject



69
70
71
# File 'lib/qtrix/queue.rb', line 69

def resource_percentage
  @resource_percentage ||= weight.to_f / self.class.total_weight(namespace)
end

#weightObject



73
74
75
# File 'lib/qtrix/queue.rb', line 73

def weight
  @weight ||= redis(namespace).zscore(REDIS_KEY, name).to_f
end