Sha256: c8f7c9a6a3ed2ec7a6da049aabcb40f076e064426e4ae63c5052f58109a72961

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

require 'nokogiri'
class ActsAsContentHighlightable::HtmlNodeParser
  def initialize(content)
    @content = content
    @parsed = Nokogiri::HTML.parse(@content)
  end

  attr_accessor :content, :parsed

  def assign_unique_node_identifiers(attribute_name)
    @running_unique_identifiers = Array.new
    apply_unique_identifiers_to_children(@parsed, attribute_name)
    return self
  end

  def body_content
    return @parsed.css('body').inner_html
  end

  private

  def apply_unique_identifiers_to_children(node, attribute_name)
    node.children.each do |node|
      if node[attribute_name].blank?
        unique_id = get_unique_key(@running_unique_identifiers)
        node[attribute_name] = unique_id
      end
      @running_unique_identifiers.push(node[attribute_name])
      node = apply_unique_identifiers_to_children(node, attribute_name)
    end
    return node
  end

  def get_unique_key(existing_array)
    unique_id = SecureRandom.hex(4)
    max_iter = 100
    iter = 0
    while(existing_array.include? unique_id and iter < max_iter)
      unique_id = (iter > max_iter/2) ? SecureRandom.hex(5) : SecureRandom.hex(4)
      iter += 1
      end
    return unique_id
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
acts_as_content_highlightable-0.1.0 lib/acts_as_content_highlightable/html_node_parser.rb