Autolink emails and URLs at rendering time
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
module HtmlHelper
|
||||
def format_html(html)
|
||||
fragment = Nokogiri::HTML.fragment(html)
|
||||
|
||||
auto_link(fragment)
|
||||
|
||||
fragment.to_html.html_safe
|
||||
end
|
||||
|
||||
private
|
||||
EXCLUDED_ELEMENTS = %w[ a figcaption pre code ]
|
||||
EMAIL_REGEXP = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/
|
||||
URL_REGEXP = URI::DEFAULT_PARSER.make_regexp(%w[http https])
|
||||
|
||||
def auto_link(fragment)
|
||||
fragment.traverse do |node|
|
||||
next unless auto_linkable_node?(node)
|
||||
|
||||
content = node.text
|
||||
linked_content = content.dup
|
||||
|
||||
auto_link_urls(linked_content)
|
||||
auto_link_emails(linked_content)
|
||||
|
||||
if linked_content != content
|
||||
node.replace(Nokogiri::HTML.fragment(linked_content))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def auto_linkable_node?(node)
|
||||
node.text? && node.ancestors.none? { |ancestor| EXCLUDED_ELEMENTS.include?(ancestor.name) }
|
||||
end
|
||||
|
||||
def auto_link_urls(linked_content)
|
||||
linked_content.gsub!(URL_REGEXP) do |match|
|
||||
%(<a href="#{match}" rel="noreferrer">#{match}</a>)
|
||||
end
|
||||
end
|
||||
|
||||
def auto_link_emails(text)
|
||||
text.gsub!(EMAIL_REGEXP) do |match|
|
||||
%(<a href="mailto:#{match}">#{match}</a>)
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user