Class: Dynflow::Semaphores::Stateful

Inherits:
Abstract
  • Object
show all
Defined in:
lib/dynflow/semaphores/stateful.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tickets, free = tickets, meta = {}) ⇒ Stateful

Returns a new instance of Stateful.



8
9
10
11
12
13
# File 'lib/dynflow/semaphores/stateful.rb', line 8

def initialize(tickets, free = tickets, meta = {})
  @tickets = tickets
  @free = free
  @waiting = []
  @meta = meta
end

Instance Attribute Details

#freeObject (readonly)

Returns the value of attribute free.



6
7
8
# File 'lib/dynflow/semaphores/stateful.rb', line 6

def free
  @free
end

#metaObject (readonly)

Returns the value of attribute meta.



6
7
8
# File 'lib/dynflow/semaphores/stateful.rb', line 6

def meta
  @meta
end

#ticketsObject (readonly)

Returns the value of attribute tickets.



6
7
8
# File 'lib/dynflow/semaphores/stateful.rb', line 6

def tickets
  @tickets
end

#waitingObject (readonly)

Returns the value of attribute waiting.



6
7
8
# File 'lib/dynflow/semaphores/stateful.rb', line 6

def waiting
  @waiting
end

Class Method Details

.new_from_hash(hash) ⇒ Object



66
67
68
# File 'lib/dynflow/semaphores/stateful.rb', line 66

def self.new_from_hash(hash)
  self.new(*hash.values_at(:tickets, :free, :meta))
end

Instance Method Details

#drainObject



51
52
53
54
55
56
# File 'lib/dynflow/semaphores/stateful.rb', line 51

def drain
  @free.tap do
    @free = 0
    save
  end
end

#get(n = 1) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/dynflow/semaphores/stateful.rb', line 41

def get(n = 1)
  if n > @free
    drain
  else
    @free -= n
    save
    n
  end
end

#get_waitingObject



24
25
26
# File 'lib/dynflow/semaphores/stateful.rb', line 24

def get_waiting
  @waiting.shift
end

#has_waiting?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/dynflow/semaphores/stateful.rb', line 28

def has_waiting?
  !@waiting.empty?
end

#release(n = 1) ⇒ Object



32
33
34
35
36
# File 'lib/dynflow/semaphores/stateful.rb', line 32

def release(n = 1)
  @free += n
  @free = @tickets unless @tickets.nil? || @free <= @tickets
  save
end

#saveObject



38
39
# File 'lib/dynflow/semaphores/stateful.rb', line 38

def save
end

#to_hashObject



58
59
60
61
62
63
64
# File 'lib/dynflow/semaphores/stateful.rb', line 58

def to_hash
  {
    :tickets => @tickets,
    :free => @free,
    :meta => @meta
  }
end

#wait(thing) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/dynflow/semaphores/stateful.rb', line 15

def wait(thing)
  if get > 0
    true
  else
    @waiting << thing
    false
  end
end