Method: MarkupHelper#link_to_html

Defined in:
app/helpers/markup_helper.rb

It solves a problem occurring with nested links (i.e. “<a>outer text <a>gfm ref</a> more outer text</a>”). This will not be interpreted as intended. Browsers will parse something like “<a>outer text </a><a>gfm ref</a> more outer text” (notice the last part is not linked any more). link_to_html corrects that. It wraps all parts to explicitly produce the correct linking behavior (i.e. “<a>outer text </a><a>gfm ref</a><a> more outer text</a>”).



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
54
55
56
# File 'app/helpers/markup_helper.rb', line 29

def link_to_html(redacted, url, html_options = {})
  fragment = Nokogiri::HTML::DocumentFragment.parse(redacted)

  if fragment.children.size == 1 && fragment.children[0].name == 'a'
    # Fragment has only one node, and it's a link generated by `gfm`.
    # Replace it with our requested link.
    text = fragment.children[0].text
    fragment.children[0].replace(link_to(text, url, html_options))
  else
    # Traverse the fragment's first generation of children looking for
    # either pure text or emojis, wrapping anything found in the
    # requested link
    fragment.children.each do |node|
      if node.text?
        node.replace(link_to(node.text, url, html_options))
      elsif node.name == 'gl-emoji'
        node.replace(link_to(node.to_html.html_safe, url, html_options))
      end
    end
  end

  # Add any custom CSS classes to the GFM-generated reference links
  if html_options[:class]
    fragment.css('a.gfm').add_class(html_options[:class])
  end

  fragment.to_html.html_safe
end