Sha256: 76093af651e09f6c306389e1426a288c3d92c086f4ed85d0566b2ffe5467ab02

Contents?: true

Size: 1.31 KB

Versions: 8

Compression:

Stored size: 1.31 KB

Contents

module Erlectricity
  class Receiver
    attr_accessor :port
    attr_accessor :parent
    attr_accessor :matchers

    RECEIVE_LOOP = Object.new
    NO_MATCH = Object.new

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

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

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

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

    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

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

    def receive_loop
      RECEIVE_LOOP
    end

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

module Kernel
  def receive(input = nil, output = nil, &block)
    input ||= IO.new(3)
    output ||= IO.new(4)
    Erlectricity::Receiver.new(Erlectricity::Port.new(input, output), nil, &block).run
  end
end

Version data entries

8 entries across 8 versions & 3 rubygems

Version Path
mojombo-erlectricity-1.0.0 lib/erlectricity/receiver.rb
mojombo-erlectricity-1.0.1 lib/erlectricity/receiver.rb
mojombo-erlectricity-1.0.2 lib/erlectricity/receiver.rb
erlectricity-funbox-1.1.2 lib/erlectricity/receiver.rb
erlectricity-1.1.1 lib/erlectricity/receiver.rb
erlectricity-1.1.0 lib/erlectricity/receiver.rb
erlectricity-1.0.0 lib/erlectricity/receiver.rb
erlectricity-1.0.1 lib/erlectricity/receiver.rb