Class: Cod::SelectGroup

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

Overview

A select group is a special kind of hash, basically. It contains group names as keys (probably symbols) and has either array values or single object instances.

A number of operations is defined to make it easier to filter such hashes during IO.select. The API user only ever gets to see the resulting hash.

Instance Method Summary collapse

Constructor Details

#initialize(hash_or_value) ⇒ SelectGroup

:nodoc:



11
12
13
14
15
16
17
18
19
# File 'lib/cod/select_group.rb', line 11

def initialize(hash_or_value)
  if hash_or_value.respond_to?(:each)
    @h = hash_or_value
    @unpack = false
  else
    @h = {box: hash_or_value}
    @unpack = true
  end
end

Instance Method Details

#emptyObject

Returns something that will represent the empty result to our client. If this class was constructed with just a single object, the empty result is nil. Otherwise the empty result is an empty hash.



79
80
81
82
83
84
85
# File 'lib/cod/select_group.rb', line 79

def empty
  if @unpack
    nil
  else
    {}
  end
end

#keep_if(&block) ⇒ Object

Keeps values around with their respective keys if block returns true for the values. Deletes everything else. NOT like Hash#keep_if.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cod/select_group.rb', line 40

def keep_if(&block)
  old_hash = @h
  @h = Hash.new
  old_hash.each do |key, values|
    # Now values is either an Array like structure that we iterate 
    # on or it is a single value. 
    if values.respond_to?(:to_ary)
      ary = values.select { |e| block.call(e) }
      @h[key] = ary unless ary.empty?
    else
      value = values
      @h[key] = value if block.call(value)
    end
  end
  
  self
end

#keysObject

EXACTLY like Hash#keys.



59
60
61
# File 'lib/cod/select_group.rb', line 59

def keys
  @h.keys
end

#unpackObject

Converts this to a result value. If this instance was constructed with a simple ruby object, return the object. Otherwise return the resulting hash.



67
68
69
70
71
72
73
# File 'lib/cod/select_group.rb', line 67

def unpack
  if @unpack
    @h[:box]
  else
    @h
  end
end

#values(&block) ⇒ Object

Returns all values as a single flat array. NOT like Hash#values.



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/cod/select_group.rb', line 23

def values(&block)
  values = []
  block ||= lambda { |e| e } # identity
  
  @h.each do |_,v|
    if v.respond_to?(:to_ary)
      values << v.map(&block)
    else
      values << block.call(v)
    end
  end
  values.flatten
end