Class: Expect::PatternList

Inherits:
Object
  • Object
show all
Defined in:
lib/expect/pattern_list.rb

Overview

将 Ruby 模式和块回调整理为有序会话组;注册阶段不读取 IO、不执行匹配回调。 分组结构直接决定 Matcher 的“声明组 → 会话 → 模式”优先级,不能按匹配位置重排。

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sessions = [], patterns = []) ⇒ PatternList

建立默认来源,并将位置参数中的文本、正则、:eof、:timeout 转成统一模式。



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/expect/pattern_list.rb', line 10

def initialize(sessions = [], patterns = [])
  @default_sessions = Array(sessions).dup
  validate_sessions!(@default_sessions) unless @default_sessions.empty?
  # 保留空模式的默认会话组,使 expect(timeout:) 也能只收集输出而不匹配文本。
  @groups = @default_sessions.empty? ? [] : [[@default_sessions, []]]
  @number = 0
  patterns.each do |value|
    case value
    when :eof then eof
    when :timeout then timeout
    else on(value)
    end
  end
end

Instance Attribute Details

#groups ⇒ Object (readonly)

Returns the value of attribute groups.



7
8
9
# File 'lib/expect/pattern_list.rb', line 7

def groups
  @groups
end

#timeout_pattern ⇒ Object (readonly)

Returns the value of attribute timeout_pattern.



7
8
9
# File 'lib/expect/pattern_list.rb', line 7

def timeout_pattern
  @timeout_pattern
end

Instance Method Details

#eof(from: @default_sessions, &block) ⇒ Object

为指定来源注册 EOF 回调;实例 DSL 默认使用当前会话。



33
34
35
# File 'lib/expect/pattern_list.rb', line 33

def eof(from: @default_sessions, &block)
  add(:eof, from, block)
end

#eof_patterns_for(session) ⇒ Object

收集指定会话的所有 EOF 处理器,保留原注册顺序。



51
52
53
54
55
# File 'lib/expect/pattern_list.rb', line 51

def eof_patterns_for(session)
  groups.flat_map do |sessions, patterns|
    sessions.include?(session) ? patterns.select(&:eof?) : []
  end
end

#on(value, from: @default_sessions, &block) ⇒ Object

注册文本模式;字符串始终字面匹配并复制冻结,避免注册后被外部修改。

Raises:

  • (ArgumentError)


26
27
28
29
30
# File 'lib/expect/pattern_list.rb', line 26

def on(value, from: @default_sessions, &block)
  raise ArgumentError, "pattern must be a String or Regexp" unless value.is_a?(String) || value.is_a?(Regexp)

  add(value.is_a?(String) ? value.b.freeze : value, from, block)
end

#sessions ⇒ Object

汇总并去重读取源,同一会话出现在多个模式组时仍只读取一次。 这里只去重会话对象;不同会话包装同一 IO 时的读取归属由 Matcher 决定。



48
# File 'lib/expect/pattern_list.rb', line 48

def sessions = groups.flat_map(&:first).uniq

#timeout(&block) ⇒ Object

注册一次等待的唯一超时回调,重复定义直接报错,避免悄悄覆盖业务处理。 超时是整次等待的事件,回调收到全部活跃会话,不归属于某一个来源组。

Raises:

  • (ArgumentError)


39
40
41
42
43
44
# File 'lib/expect/pattern_list.rb', line 39

def timeout(&block)
  raise ArgumentError, "timeout callback already registered" if @timeout_pattern

  @timeout_pattern = build(:timeout, block)
  self
end

#validate! ⇒ Object

启动引擎前确保存在读取源;类级等待必须通过 from: 明确来源。

Raises:

  • (ArgumentError)


58
59
60
61
62
# File 'lib/expect/pattern_list.rb', line 58

def validate!
  raise ArgumentError, "at least one session is required" if groups.empty?

  self
end