Class: Lich::Common::Watchfor

Inherits:
Object
  • Object
show all
Defined in:
lib/common/watchfor.rb

Overview

A class that watches for specific patterns in a script and executes a block of code when a match is found.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(line, theproc = nil, &block) ⇒ nil

Note:

This method disables a Rubocop linting rule regarding returning nil in a void context.

Initializes a new Watchfor instance.

rubocop:disable Lint/ReturnInVoidContext

Examples:

watch = Watchfor.new("error") { puts "An error occurred!" }
watch = Watchfor.new(/warning/, some_proc) { puts "A warning occurred!" }

Parameters:

  • line (String, Regexp)

    The string or regular expression to watch for.

  • theproc (Proc, nil) (defaults to: nil)

    An optional Proc to execute when the pattern is matched.

  • block (Proc)

    A block of code to execute when the pattern is matched.

Raises:

  • (ArgumentError)

    Raises an error if the line is neither a String nor a Regexp.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/common/watchfor.rb', line 21

def initialize(line, theproc = nil, &block)
  return nil unless (script = Script.current)

  if line.class == String
    line = Regexp.new(Regexp.escape(line))
  elsif line.class != Regexp
    echo 'watchfor: no string or regexp given'
    return nil
  end
  if block.nil?
    if theproc.respond_to? :call
      block = theproc
    else
      echo 'watchfor: no block or proc given'
      return nil
    end
  end
  script.watchfor[line] = block
end

Class Method Details

.clearnil

Note:

This method resets the watchfor hash to a new empty hash.

Clears all watchfor patterns from the current script.

Examples:

Watchfor.clear

Returns:

  • (nil)

    Returns nil after clearing the patterns.



50
51
52
# File 'lib/common/watchfor.rb', line 50

def Watchfor.clear
  script.watchfor = Hash.new
end