Class: EventExpectr

Inherits:
Object
  • Object
show all
Defined in:
lib/event-expectr.rb,
lib/event-expectr/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cmd, args = {}) ⇒ EventExpectr

Returns a new instance of EventExpectr.



14
15
16
17
18
19
20
21
# File 'lib/event-expectr.rb', line 14

def initialize(cmd, args={})
  @timeout = args.delete(:timeout) || 30
  
  @expectr = Expectr.new(cmd, args)
  @expectr.timeout = 0.01

  @patterns = {}
end

Instance Attribute Details

#expectrObject (readonly)

Expectr instance this class wraps



9
10
11
# File 'lib/event-expectr.rb', line 9

def expectr
  @expectr
end

#patternsObject (readonly)

hash of patterns mapping to code blocks to execute when they match



6
7
8
# File 'lib/event-expectr.rb', line 6

def patterns
  @patterns
end

#runningObject

boolean value that keeps the run! method running. set to false to bail out.



12
13
14
# File 'lib/event-expectr.rb', line 12

def running
  @running
end

Instance Method Details

#expect(pattern, &block) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/event-expectr.rb', line 23

def expect(pattern, &block)
  if not [String, Regexp].include? pattern.class
    raise TypeError, "Pattren class should be String or Regexp"
  end

  @patterns[pattern] = block
end

#run!Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/event-expectr.rb', line 31

def run!
  if @patterns.count == 0
    raise RuntimeError, "No patterns have been defined yet, this would just look forever"
  end

  @running = true

  begin
    Timeout::timeout(@timeout) do
      while @running
        @patterns.each_pair do |pattern, block|
          match = @expectr.expect(pattern, true)
          if match
            # run the code provided with this pattern
            block.call(match)

            # remove it so we don't try to match again
            @patterns.delete(pattern)

            # the code block may have turned this off
            break unless @running
          end

          @running = false if @patterns.count == 0
        end

        sleep 0.1
      end
    end
  rescue Timeout::Error
    # haven't found all the matches in the time given.  oh well.
    return false
  end

  # this is an intentional end of the run process
  return true
end