Sha256: 0edb4482936fe40f9aa8d2271b712dd9a5a42488487ed1280c4f9a0fa8690a94

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

module Wovnrb
  class ImageReplacer < ReplacerBase
    def initialize(url, text_index, src_index, img_src_prefix)
      @url = url
      @text_index = text_index
      @src_index = src_index
      @img_src_prefix = img_src_prefix
    end

    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 = "#{@url[:protocol]}://#{@url[:host]}#{src}"
            else
              src = "#{@url[:protocol]}://#{@url[:host]}#{@url[:path]}#{src}"
            end
          end

          # shouldn't need size check, but for now...
          if @src_index[src] && @src_index[src][lang.lang_code] && @src_index[src][lang.lang_code].size > 0
            node.attribute('src').value = "#{@img_src_prefix}#{@src_index[src][lang.lang_code][0]['data']}"
          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
            node.attribute('alt').value = alt.gsub(/^(\s*)[\S\s]*(\s*)$/, '\1' + @text_index[alt][lang.lang_code][0]['data'] + '\2')
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
wovnrb-0.2.02 lib/wovnrb/html_replacers/image_replacer.rb