Class: Bypass::HTMLFilter

Inherits:
Filter
  • Object
show all
Defined in:
lib/bypass/html_filter.rb

Constant Summary

Constants inherited from Filter

Filter::URL_PATTERN

Instance Attribute Summary

Attributes inherited from Filter

#fragment

Instance Method Summary collapse

Methods inherited from Filter

#to_s

Constructor Details

#initialize(content, options = {}) ⇒ HTMLFilter

Returns a new instance of HTMLFilter.



6
7
8
9
10
11
12
13
14
15
# File 'lib/bypass/html_filter.rb', line 6

def initialize(content, options = {})
  if content.respond_to?(:traverse) # then this is Nokogiri
    @content = content
    @parsed_content = content
  else
    @content = content.to_s.encode("UTF-8")
  end

  @fragment = options.fetch(:fragment, true)
end

Instance Method Details



28
29
30
31
32
33
34
35
# File 'lib/bypass/html_filter.rb', line 28

def auto_link(options = {})
  each_text_node do |node|
    text = gsub_urls(node.text.to_s) do |url|
      build_anchor_tag(url, url, options)
    end
    node.replace(parse_html_fragment(text))
  end
end

#build_anchor_tag(text, href, options = {}) ⇒ Object



37
38
39
40
41
# File 'lib/bypass/html_filter.rb', line 37

def build_anchor_tag(text, href, options = {})
  attributes = []
  options.each { |k, v| attributes << " #{k}=\"#{v}\"" }
  "<a href=\"#{href}\"#{attributes.join(' ')}>#{text}</a>"
end

#contentObject



47
48
49
# File 'lib/bypass/html_filter.rb', line 47

def content
  parsed_content.to_s
end

#parse_contentObject



51
52
53
54
55
56
57
# File 'lib/bypass/html_filter.rb', line 51

def parse_content
  if fragment
    parse_html_fragment(@content)
  else
    parse_html_document(@content)
  end
end

#parsed_contentObject



43
44
45
# File 'lib/bypass/html_filter.rb', line 43

def parsed_content
  @parsed_content ||= parse_content
end

#replace(&block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/bypass/html_filter.rb', line 17

def replace(&block)
  parsed_content.traverse do |node|
    if node.name == "a" && href = node.get_attribute("href")
      if parsed_href = parse_uri(href)
        url = yield(parsed_href)
        node.set_attribute("href", url.to_s)
      end
    end
  end
end