Sha256: 9abb7e0fdf0169c3efd4a93f952a1ad7f3d4da26064bcb439cbb490806f2a450

Contents?: true

Size: 860 Bytes

Versions: 5

Compression:

Stored size: 860 Bytes

Contents

class Mangos::TagBreaker
  DELIMITERS = [
    ['(', ')'],
    ['[', ']'],
    ['{', '}'],
    ['<', '>']
  ]

  def initialize(text)
    @text = text
  end

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

  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
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mangos-0.5 lib/mangos/tag_breaker.rb
mangos-0.4 lib/mangos/tag_breaker.rb
mangos-0.3 lib/mangos/tag_breaker.rb
mangos-0.2 lib/mangos/tag_breaker.rb
mangos-0.1 lib/mangos/tag_breaker.rb