Module: Jekyll::ExtLinks

Defined in:
lib/jekyll-extlinks.rb

Instance Method Summary collapse

Instance Method Details

#configObject

Access plugin config in _config.yml



28
29
30
# File 'lib/jekyll-extlinks.rb', line 28

def config
  @context.registers[:site].config['extlinks']
end

#contains_any(str, fragments) ⇒ Object

Checks if str contains any fragment of the fragments array



33
34
35
36
# File 'lib/jekyll-extlinks.rb', line 33

def contains_any(str, fragments)
  return false unless Regexp.union(fragments) =~ str
  true
end


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/jekyll-extlinks.rb', line 38

def extlinks(content)
  # Process configured link attributes and whitelisted hosts
  if config
    if config['attributes']
      attributes = Array(config['attributes'])
    end
    if config['rel_exclude']
      rel_exclude = Array(config['rel_exclude'])
    end
  end
  # Stop if no attributes were specified
  return content unless attributes

  doc = Nokogiri::HTML.parse(content)
  # Stop if we could't parse with HTML
  return content unless doc

  doc.css('a').each do |a|
    # If this is a local link don't change it
    next unless a.get_attribute('href') =~ /\Ahttp/i

    attributes.each do |attr, value|
      if attr.downcase == 'rel'
        # If there's a rel already don't change it
        next unless !a.get_attribute('rel') || a.get_attribute('rel').empty?
        # Skip whitelisted hosts for the 'rel' attribute
        next if rel_exclude && contains_any(a.get_attribute('href'), rel_exclude)
      end
      a.set_attribute(attr, value)
    end
  end

  doc.to_s
end