about summary refs log tree commit diff
path: root/app/lib/img_tag_handler.rb
blob: 0263e1cbd52eb9ea8013f0b61463c54e5e946508 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# frozen_string_literal: true

class ImgTagHandler < ::Ox::Sax
  attr_reader :srcs
  attr_reader :alts

  def initialize
    @stack = []
    @srcs = []
    @alts = {}
  end

  def start_element(element_name)
    @stack << [element_name, {}]
  end

  def end_element(_)
    self_name, self_attributes = @stack[-1]
    if self_name == :img && !self_attributes[:src].nil?
      @srcs << self_attributes[:src]
      @alts[self_attributes[:src]] = self_attributes[:alt]&.strip
    end
    @stack.pop
  end

  def attr(attribute_name, attribute_value)
    _name, attributes = @stack.last
    attributes[attribute_name] = attribute_value&.strip
  end
end