Class: FuelSurcharge::HTMLScanner

Inherits:
Object
  • Object
show all
Defined in:
lib/fuel_surcharge/html_scanner.rb

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ HTMLScanner

Returns a new instance of HTMLScanner.



7
8
9
# File 'lib/fuel_surcharge/html_scanner.rb', line 7

def initialize(source)
  @scanner = StringScanner.new(source.to_s)
end

Instance Method Details

#all(tag, attribute = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/fuel_surcharge/html_scanner.rb', line 25

def all(tag, attribute = nil)
  chunks = []
  return chunks if @scanner.eos?

  while (chunk = upcoming(tag, attribute))
    chunks << chunk
  end
  chunks
end

#upcoming(tag, attribute = nil) ⇒ Object



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

def upcoming(tag, attribute = nil)
  return if @scanner.eos?

  opening = attribute ? "<#{tag}\s[^>]*#{attribute}[^>]*>" : "<#{tag}[^>]*>"
  closing = "</#{tag}>"
  return unless @scanner.exist?(/#{opening}/) && @scanner.exist?(/#{closing}/)

  current_pos = @scanner.pos
  @scanner.skip_until(/#{opening}/)
  chunk = @scanner.scan_until(/#{closing}/).to_s
  @scanner.pos = current_pos if chunk.empty?
  chunk[0...chunk.size - closing.size].strip
end