Class: RuPol::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max, klass) ⇒ Pool

Returns a new instance of Pool.



6
7
8
9
10
11
12
13
# File 'lib/pool.rb', line 6

def initialize(max, klass)
  self.max_size = max
  self.instance_class = klass
  self.cache = []
  self.stats = empty_stats
  self.recycledable = class_has_method?(:_recycled)
  self.clearable = class_has_method?(:clear)
end

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



3
4
5
# File 'lib/pool.rb', line 3

def cache
  @cache
end

#clearableObject

Returns the value of attribute clearable.



3
4
5
# File 'lib/pool.rb', line 3

def clearable
  @clearable
end

#instance_classObject

Returns the value of attribute instance_class.



3
4
5
# File 'lib/pool.rb', line 3

def instance_class
  @instance_class
end

#max_sizeObject

Returns the value of attribute max_size.



3
4
5
# File 'lib/pool.rb', line 3

def max_size
  @max_size
end

#recycledableObject

Returns the value of attribute recycledable.



3
4
5
# File 'lib/pool.rb', line 3

def recycledable
  @recycledable
end

#statsObject

Returns the value of attribute stats.



3
4
5
# File 'lib/pool.rb', line 3

def stats
  @stats
end

Instance Method Details

#available?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/pool.rb', line 43

def available?
  size < max_size
end

#class_has_method?(meth) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/pool.rb', line 15

def class_has_method?(meth)
  instance_class.instance_methods.include?(meth.to_s)
end

#empty!Object



60
61
62
63
# File 'lib/pool.rb', line 60

def empty!
  self.stats = empty_stats
  cache.clear
end

#empty_statsObject



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

def empty_stats
  {
    :gets => 0,
    :pushes => 0,
    :overage => 0
  }
end

#include?(value) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/pool.rb', line 47

def include?(value)
  cache.include?(value)
end

#push(value) ⇒ Object Also known as: <<



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/pool.rb', line 31

def push(value)
  if available?
    stats[:pushes] += 1 
    value.clear if clearable
    value._recycled = true if recycledable
    cache.push( value )
  else
    stats[:overage] += 1
  end
  value 
end

#shiftObject Also known as: get



51
52
53
54
55
56
57
58
# File 'lib/pool.rb', line 51

def shift
  instance = cache.shift
  if instance
    stats[:gets] += 1
    instance._recycled = false if instance.respond_to?(:_recycled)
    instance
  end
end

#sizeObject



27
28
29
# File 'lib/pool.rb', line 27

def size
  cache.size
end