Class: Erlectricity::Receiver

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

Constant Summary collapse

RECEIVE_LOOP =
Object.new
NO_MATCH =
Object.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port, parent = nil, &block) ⇒ Receiver

Returns a new instance of Receiver.



10
11
12
13
14
15
# File 'lib/erlectricity/receiver.rb', line 10

def initialize(port, parent = nil, &block)
  @port = port
  @parent = parent
  @matchers = []
  block.call(self) if block
end

Instance Attribute Details

#matchersObject

Returns the value of attribute matchers.



5
6
7
# File 'lib/erlectricity/receiver.rb', line 5

def matchers
  @matchers
end

#parentObject

Returns the value of attribute parent.



4
5
6
# File 'lib/erlectricity/receiver.rb', line 4

def parent
  @parent
end

#portObject

Returns the value of attribute port.



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

def port
  @port
end

Instance Method Details

#process(arg) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/erlectricity/receiver.rb', line 17

def process(arg)
  matcher = @matchers.find { |r| r.matches?(arg) }

  if matcher
    port.restore_skipped
    matcher.run(arg)
  else
    NO_MATCH
  end
end

#receive(&block) ⇒ Object



49
50
51
# File 'lib/erlectricity/receiver.rb', line 49

def receive(&block)
  Receiver.new(port, self, &block).run
end

#receive_loopObject



53
54
55
# File 'lib/erlectricity/receiver.rb', line 53

def receive_loop
  RECEIVE_LOOP
end

#runObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/erlectricity/receiver.rb', line 33

def run
  loop do
    msg = port.receive
    return if msg.nil?

    case result = process(msg)
      when RECEIVE_LOOP then next
      when NO_MATCH
        port.skipped << msg
        next
      else
        break result
    end
  end
end

#send!(term) ⇒ Object



57
58
59
# File 'lib/erlectricity/receiver.rb', line 57

def send!(term)
  port.send(term)
end

#when(arg, &block) ⇒ Object



28
29
30
31
# File 'lib/erlectricity/receiver.rb', line 28

def when(arg, &block)
  condition = Condition.for(arg)
  @matchers << Matcher.new(self, condition, block)
end