Class: Cod::Select

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

Overview

Performs an IO.select on a list of file descriptors and Cod channels. Construct this like so:

Select.new(
  0.1,                    # timeout
  foo: single_fd,         # a single named FD
  bar: [one, two, three], # a group of FDs.
)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timeout, groups) ⇒ Select

Returns a new instance of Select.



19
20
21
22
# File 'lib/cod/select.rb', line 19

def initialize(timeout, groups)
  @timeout = timeout
  @groups = SelectGroup.new(groups)
end

Instance Attribute Details

#groupsObject (readonly)

Returns the value of attribute groups.



17
18
19
# File 'lib/cod/select.rb', line 17

def groups
  @groups
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



16
17
18
# File 'lib/cod/select.rb', line 16

def timeout
  @timeout
end

Instance Method Details

#doObject

Performs the IO.select and returns a thinned out version of that initial groups, containing only FDs and channels that are ready for reading.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cod/select.rb', line 27

def do
  fds = groups.values { |e| to_read_fd(e) }
  
  # Perform select  
  r,w,e = IO.select(fds, nil, nil, timeout)

  # Nothing is ready if r is nil
  return groups.empty unless r
  
  # Prepare a return value: The original hash, where the fds are ready.
  groups.
    keep_if { |e| r.include?(to_read_fd(e)) }.
    unpack
end