Module: StringTools::HTML
- Defined in:
- lib/string_tools/html.rb
Defined Under Namespace
Classes: LinksRemoveScrubber
Constant Summary collapse
- TEXT_WITH_LINKS_MINIMUM_LENGTH =
минимальная длина строки, в которой могут быть ссылки
'<a href="'.length
- HTML_SERIALIZE_OPTIONS =
{ indent: 0, # сериализуем в xhtml, поскольку при сериализации в html, libxml2 делает чуть больше, чем хотелось бы: # http://stackoverflow.com/questions/24174032/prevent-nokogiri-from-url-encoding-src-attributes save_with: Nokogiri::XML::Node::SaveOptions::AS_XHTML }
Class Method Summary collapse
-
.remove_links(html, options = {}) ⇒ Object
Public: Удаляет ссылки на неразрешенные домены.
Class Method Details
.remove_links(html, options = {}) ⇒ Object
Public: Удаляет ссылки на неразрешенные домены
html - String содержимое потенциально ненужных ссылок options - Hash
:whitelist - Array of String разрешенныe домены
Examples
html = '<a href="https://www.yandex.ru">yandex</a>'
StringTools::HTML.remove_links(html, whitelist: ['google.com'])
# => 'yandex'
StringTools::HTML.remove_links(html, whitelist: ['yandex.ru'])
# => '<a href="https://www.yandex.ru">yandex</a>'
StringTools::HTML.remove_links(html, whitelist: ['www.yandex.ru'])
# => '<a href="https://www.yandex.ru">yandex</a>'
html = '<a href="https://yandex.ru">yandex</a>'
StringTools::HTML.remove_links(html, whitelist: ['www.yandex.ru'])
# => 'yandex'
Returns String without links to external resources
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/string_tools/html.rb', line 42 def self.remove_links(html, = {}) return html if html.length < TEXT_WITH_LINKS_MINIMUM_LENGTH doc = Nokogiri::HTML::DocumentFragment.parse(html) scrubber = LinksRemoveScrubber.new() doc.css('a').each { |node| scrubber.call node } if scrubber.done_changes? doc.children.map { |node| node.serialize HTML_SERIALIZE_OPTIONS }.join else html end end |