Class: Wovnrb::ImageReplacer

Inherits:
ReplacerBase show all
Defined in:
lib/wovnrb/html_replacers/image_replacer.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, text_index, src_index, img_src_prefix, host_aliases) ⇒ ImageReplacer

Returns a new instance of ImageReplacer.



3
4
5
6
7
8
9
# File 'lib/wovnrb/html_replacers/image_replacer.rb', line 3

def initialize(url, text_index, src_index, img_src_prefix, host_aliases)
  @url = url
  @text_index = text_index
  @src_index = src_index
  @img_src_prefix = img_src_prefix
  @host_aliases = host_aliases
end

Instance Method Details

#replace(dom, lang) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/wovnrb/html_replacers/image_replacer.rb', line 11

def replace(dom, lang)
  dom.xpath('//img').each do |node|
    next if wovn_ignore?(node)

    # use regular expressions to support case insensitivity (right?)
    if node.to_html =~ /src=['"][^'"]*['"]/i
      src = node.to_html.match(/src=['"]([^'"]*)['"]/i)[1]
      # THIS SRC CORRECTION DOES NOT HANDLE ONE IMPORTANT CASE
      # 1) "../path/with/ellipse"
      # if this is not an absolute src
      if src !~ /:\/\//
        # if this is a path with a leading slash
        if src =~ /^\//
          src = join_path("#{@url[:protocol]}://#{@url[:host]}", src)
        else
          src = join_path("#{@url[:protocol]}://#{@url[:host]}#{@url[:path]}", src)
        end
      end

      unless replace_src_if_match(node, lang, src)
        # host name exclude port number
        host_match = %r!://([^/:]+)!.match(src)
        host_name = host_match ? host_match[1] : ''

        # replace image if match host alias
        if host_match and @host_aliases.include?(host_name)
          @host_aliases.find do |host_alias|
            src_alias = src.gsub(host_name, host_alias)
            replace_src_if_match(node, lang, src_alias)
          end
        end
      end
    end

    if node.get_attribute('alt')
      alt = node.get_attribute('alt').strip
      if @text_index[alt] && @text_index[alt][lang.lang_code] && @text_index[alt][lang.lang_code].size > 0
        add_comment_node(node, alt)
        node.attribute('alt').value = replace_text(alt, @text_index[alt][lang.lang_code][0]['data'])
      end
    end
  end
end