Class: Zerg::Support::Sockets::ReceiveMock

Inherits:
Object
  • Object
show all
Defined in:
lib/zerg_support/sockets/socket_mocks.rb

Overview

Mocks the receiving end of a Socket connection. The data to be received is passed as an array of strings to the constructor.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(strings = ['']) ⇒ ReceiveMock

Returns a new instance of ReceiveMock.



24
25
26
27
# File 'lib/zerg_support/sockets/socket_mocks.rb', line 24

def initialize(strings = [''])
  @strings = strings.kind_of?(String) ? [strings] : strings
  @objects = []
end

Instance Attribute Details

#objectsObject

Returns the value of attribute objects.



22
23
24
# File 'lib/zerg_support/sockets/socket_mocks.rb', line 22

def objects
  @objects
end

#stringsObject

Returns the value of attribute strings.



21
22
23
# File 'lib/zerg_support/sockets/socket_mocks.rb', line 21

def strings
  @strings
end

Class Method Details

.object_name(name) ⇒ Object

Declares the name of the object to be received. For instance, a frame protocol would use :frame for name. This generates a receive_frame method, and a frames accessor.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/zerg_support/sockets/socket_mocks.rb', line 42

def self.object_name(name)
  # Calls recv_object until the bytes buffer is drained.
  define_method :replay do
    while @strings.length > 0
      @objects << self.send(:"recv_#{name}")
    end
    loop do
      object = self.send(:"recv_#{name}")
      break unless object
      @objects << object
    end
    self
  end
  return if name == :object
  alias_method :"#{name}s", :objects
end

Instance Method Details

#recv(byte_limit) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/zerg_support/sockets/socket_mocks.rb', line 29

def recv(byte_limit)
  bytes = @strings.shift
  return '' unless bytes
  if bytes.length > byte_limit
    @strings.unshift bytes[byte_limit, bytes.length]
    bytes = bytes[0, byte_limit]
  end
  bytes
end