Class: TagExtractor::HTMLExtractor

Inherits:
StringExtractor show all
Defined in:
lib/tag_extractor.rb

Overview

Public: A class holding methods to handle tags extraction and manipulation from HTML Strings. Inherits from StringExtractor.

Instance Attribute Summary

Attributes inherited from StringExtractor

#source

Instance Method Summary collapse

Methods inherited from StringExtractor

#extract, #extract_with_separator, #initialize

Constructor Details

This class inherits a constructor from TagExtractor::StringExtractor

Instance Method Details

Public: Add links around all tags in an HTML String.

separator - A specific separator, as a String. If none specified, it defaults to the global separator. container - A specific container, as a String. If none specified, it defaults to the default or global container. options - An Hash of options for the link extraction (default: { class => nil }).

:class     - A String css class to add to the <a> link tag.
:multiword - A Boolean to indicate if multiple words tags are to be extracted.

block - A Block used to specify a link dynamicaly. It is passed the cleaned tag string and it should return a String to be injected in the href attribute.

Examples

# Considering the following string has been used for instanciation :
# 'This is a string with #tag1, #tag2'
html_extractor.convert_tags_to_html_links('#', :class => 'tag tag-link') do |tag_string|
  "/tag/#{tag_string}.downcase"
end
# => 'This is a string with <a class="tag tag-link" href="/tag/tag2">#tag1</a>, <a class="tag tag-link" href="/tag/tag2">#tag2</a>'

Returns an HTML String.



200
201
202
203
204
205
206
207
# File 'lib/tag_extractor.rb', line 200

def convert_tags_to_html_links(separator = nil, container = nil, options = { class: nil }, &block)
  multi = options[:multiword] || true
  @source.gsub!(get_regex(separator, container, multi)) { |name|
    name = remove_tags_container(name, container)
    link = block.call(name.slice(1..-1)) || ''
    '<a ' + (options[:class].nil? ? '' : 'class="' + options[:class] + '" ') + 'href="' + link  + '">' + name + '</a>'
  }
end