Class: Mangos::TagBreaker

Inherits:
Object
  • Object
show all
Defined in:
lib/mangos/tag_breaker.rb

Constant Summary collapse

DELIMITERS =
[
  ['(', ')'],
  ['[', ']'],
  ['{', '}'],
  ['<', '>']
]

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ TagBreaker

Returns a new instance of TagBreaker.



9
10
11
# File 'lib/mangos/tag_breaker.rb', line 9

def initialize(text)
  @text = text
end

Instance Method Details

#extract(open, close) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mangos/tag_breaker.rb', line 19

def extract(open, close)
  token_regexp = /[^#{Regexp.escape(open)}#{Regexp.escape(close)}]+/
  delimiter_regexp = /[#{Regexp.escape(open)}#{Regexp.escape(close)}]/

  scanner = StringScanner.new(@text)

  results = []
  stack = []

  until scanner.eos? do
    token = scanner.scan(token_regexp)
    stack.each { |tag| tag << token } if token

    delimiter = scanner.scan(delimiter_regexp)
    case delimiter
    when open
      stack.push('')
    when close
      results << stack.pop
    end
  end

  results.concat(stack).compact
end

#tagsObject



13
14
15
16
17
# File 'lib/mangos/tag_breaker.rb', line 13

def tags
  results = []
  DELIMITERS.each { |(open, close)| results.concat(extract(open, close)) }
  results
end