Class: Matchdoc::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/matchdoc/matcher.rb

Defined Under Namespace

Classes: FailedChunk

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject) ⇒ Matcher

Returns a new instance of Matcher.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/matchdoc/matcher.rb', line 15

def initialize(subject)
  scanner = StringScanner.new(subject)
  @match_chunks = []
  until scanner.eos?
    break unless scanner.scan_until(/\(\?[-mix]{4}:/) #regex prefix
    @match_chunks << Regexp.new(Regexp.escape(scanner.pre_match))
    regex_sub = /\((?>[^()]|(\g<0>))*\)/.match(scanner.matched+scanner.post_match).to_s
    @match_chunks << Regexp.new(regex_sub)
    scanner.pos = scanner.pos + (regex_sub.length - 7)
    scanner.string = scanner.rest
  end
end

Instance Attribute Details

#failed_chunkObject (readonly)

Returns the value of attribute failed_chunk.



13
14
15
# File 'lib/matchdoc/matcher.rb', line 13

def failed_chunk
  @failed_chunk
end

Instance Method Details

#=~(subject) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/matchdoc/matcher.rb', line 40

def =~(subject)
  begin
    match!(subject)
  rescue FailedChunk
    false
  else
    true
  end
end

#match!(subject) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/matchdoc/matcher.rb', line 28

def match!(subject)
  scanner = StringScanner.new(subject)
  scanned_chunks = []
  @match_chunks.each.with_index do |chunk, i|
    unless scanned_chunks[i] = scanner.scan(chunk)
      raise FailedChunk.new(scanner, chunk)
    end
  end

  scanned_chunks
end

#to_sObject



50
51
52
# File 'lib/matchdoc/matcher.rb', line 50

def to_s
  @match_chunks.map { |i| '/' + YAML.load(%Q(---\n"#{i.source}"\n)) + '/' }.join
end